一般介绍是,操作都是先wait, 再signal,但是如果先signal再wait,后果是怎样,找不到结论,一直怀疑这里有问题。自己做实验,发觉也没有问题。
我开启了两个线程,一个计时器,以下就是我的关键代码:
- C/C++ code
TInt CTestMultiThreadAppUi::ThreadProc1(void* pParam){ CTestMultiThreadAppUi* pApp = (CTestMultiThreadAppUi*)pParam; while(!pApp->iStop) { if(pApp->iLocked) { pApp->iLocked = false; pApp->m_cSemaphore.Wait(); } User::After(10000); } return 0;}TInt CTestMultiThreadAppUi::ThreadProc2(void* pParam){ CTestMultiThreadAppUi* pApp = (CTestMultiThreadAppUi*)pParam; while(!pApp->iStop) { if(pApp->iUnLocked) { pApp->iUnLocked = false; pApp->m_cSemaphore.Signal(); } User::After(10000); } return 0;}TInt CTestMultiThreadAppUi::TimerLoop(void* pParam){ CTestMultiThreadAppUi* pApp = (CTestMultiThreadAppUi*)pParam; pApp->iCount ++; if(pApp->iCount == 1000) pApp->iLocked = true; if(pApp->iCount == 100) pApp->iUnLocked = true; return 0;}
------解决方案--------------------------------------------------------
RSemaphore 创建后的初始值决定的,如果值少于等于0时,线程阻塞,初始值为1 .
那么先wait, 再signal,调用WAIT的线程阻塞,反过来先signal再wait,协同工作的线程都不会阻塞,
可能出现冲突