threadsynchr2.cpp
来自「MFC程序开发参考大全 【明日科技】宋坤 刘锐宁 李伟明 【丛 书 名】」· C++ 代码 · 共 61 行
CPP
61 行
#include "stdafx.h"
#include "windows.h"
int WorkerID = 10;
const int MAXWORKERID = 100;
//Declare mutex handle
HANDLE hMutex;
//Define thread function
DWORD __stdcall ThreadFunOne(LPVOID lParam)
{
for(;;)
{
WaitForSingleObject(hMutex,INFINITE);
if (WorkerID<MAXWORKERID)
{
WorkerID +=1;
Sleep(1000);
printf("ThreadOne print out: %i \n",WorkerID);
}
ReleaseMutex(hMutex);
}
return 0;
}
DWORD __stdcall ThreadFunTwo(LPVOID lParam)
{
for (;;)
{
WaitForSingleObject(hMutex,INFINITE);
if(WorkerID<MAXWORKERID)
{
WorkerID +=1;
printf("ThreadTwo print out: %i \n",WorkerID);
Sleep(1000);
}
ReleaseMutex(hMutex);
}
return 0;
}
void main()
{
//Define thread handle
HANDLE hThread1,hThread2;
//Create thread
hThread1 = ::CreateThread(NULL,0,ThreadFunOne,NULL,0,NULL);
hThread2 = ::CreateThread(NULL,0,ThreadFunTwo,NULL,0,NULL);
//Create mutex
hMutex = CreateMutex(NULL,false,"mutex");
//Close thread handle
CloseHandle(hThread1);
CloseHandle(hThread2);
//Note: Prevent process exiting
while (true)
{
;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?