点击(此处)折叠或打开
- #include <iostream>
- #include <Windows.h>
- const int Tn = 3;
- HANDLE hMutex[Tn];
- void PutStar(LPVOID param)
- {
- int w = int(param);
- int nxt = (w+1)%Tn;
- while(1)
- {
- WaitForSingleObject(hMutex[w],INFINITE);
- std::cout<<w<<std::endl;
- ReleaseMutex(hMutex[nxt]);
- }
- }
-
- int main()
- {
- HANDLE t[Tn];
- for (int i=0;i<Tn;i++)
- {
- hMutex[i] = CreateMutex(NULL,TRUE,NULL);
- t[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)PutStar,(LPVOID)i,0,NULL);
- }
- ReleaseMutex(hMutex[0]);
- WaitForMultipleObjects(Tn,t,TRUE,INFINITE);
- }
思路是:
三个线程,三个互斥信号量;
线程1输出时先等待信号量1然后释放信号量2;
线程2输出时先等待信号量2然后释放信号量3;
线程3输出时先等待信号量3然后释放信号量1;
初始时每个信号量都是占用状态,首先在主线程中释放信号量1,这样三个线程就跑起来了。