```#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex = NULL;//互斥量
//线程函数
DWORD WINAPI Fun(LPVOID lpParamter)
{
for (int i = 0; i < 10; i++)
{
//请求一个互斥量锁
WaitForSingleObject(hMutex, INFINITE);
cout << "This is the first thread fun display!" << endl;
Sleep(100);
//释放互斥量锁
ReleaseMutex(hMutex);
}
return 0L;//表示返回的是long型的0
}
DWORD WINAPI Fun1(LPVOID lpParamter)
{
for (int i = 0; i < 10; i++)
{
//请求一个互斥量锁
WaitForSingleObject(hMutex, INFINITE);
cout << "This is the second thread fun display!" << endl;
Sleep(100);
//释放互斥量锁
ReleaseMutex(hMutex);
}
return 0L;//表示返回的是long型的0
}
DWORD WINAPI Fun2(LPVOID lpParamter)
{
for (int i = 0; i < 10; i++)
{
//请求一个互斥量锁
WaitForSingleObject(hMutex, INFINITE);
cout << "This is the third thread fun display!" << endl;
Sleep(100);
cout<<endl;
//释放互斥量锁
ReleaseMutex(hMutex);
}
return 0L;//表示返回的是long型的0
}
int main()
{
//创建第一个子线程
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE,"screen");
//关闭线程句柄
CloseHandle(hThread);
//创建第二个子线程
HANDLE hThread1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE,"screen");
//关闭线程句柄
CloseHandle(hThread1);
//创建第三个子线程
HANDLE hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE,"screen");
//关闭线程句柄
CloseHandle(hThread2);
//主线程的执行路径
for (int i = 0; i < 10; i++)
{
//请求获得一个互斥量锁
WaitForSingleObject(hMutex,INFINITE);
cout << "This is main thread display!" << endl;
Sleep(100);
//释放互斥量锁
ReleaseMutex(hMutex);
}
return 0;
}
可以使用生产者,消费者模式控制,调用wait,notifyall函数通知实现。