Symbian 操作系统中的线程和进程
2010-03-18 20:57:00 来源:WEB开发网5)同步实例
Code:
1: class CMessageBuffer
2: {
3: public:
4: CMessageBuffer();
5: void AddMessage(const TDes &aMsg);
6: void GetMessages(TDes &aMsgs);
7:
8: public:
9: RMutex iMutex;
10: TDes iMsgs;
11: };
12:
13: CMessageBuffer::CMessageBuffer()
14: {
15: iMutex.CreateLocal();
16: }
17:
18: void CMessageBuffer::AddMessage(const TDes &aMsg)
19: {
20: iMutex.Wait();
21: iMsgs.Append(aMsg);
22: iMutex.Signal();
23: }
24:
25: void CMessageBuffer::GetMessages(TDes &aMsgs)
26: {
27: iMutex.Wait();
28: aMsg.Copy(iMsgs);
29: iMsgs.Zero();
30: iMutex.Signal();
31: }
32:
33: static void CMyClass::threadFunction(TAny *aPtr)
34: {
35: CMessageBuffer *msgBuffer = (CMessageBuffer *)TAny;
36: TInt count = 0;
37: TBuf<40> msg;
38:
39: while (TRUE)
40: {
41: msg.Format(“ID: %d, count: %d ”, RThread().Id(), count++);
42: msgBuffer->AddMessage(msg);
43: User::After(1000 * 1000);
44: }
45: }
在上面所述中,CMessageBuffer是一个半成品类,它允许用户增加消息到buffer中,也允许获得所有消息。
线程函数CMyClass::threadFunction负责向CMessageBuffer共享对象添加信息,这里内存分配和错误检查并没有列出,需要读者自己完成。
假设有多个线程要共享CMessageBuffer对象实例,则在实际访问 buffer时必须要同步来处理。我们也可在线程函数中完成,但在CMessageBuffer中完成同步将使得该类成为线程安全级,同样它也可以被用在单个线程中了。
更多精彩
赞助商链接