15,471
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <Windows.h>
using namespace std;
DWORD WINAPI ThreadFun1(
_In_ LPVOID lpParameter
);
DWORD WINAPI ThreadFun2(
_In_ LPVOID lpParameter
);
static UINT tickets=500;
HANDLE hMutex;
void main()
{
HANDLE hThread1;
HANDLE hThread2;
hThread1=CreateThread(NULL,0,ThreadFun1,NULL, 0,NULL);
hThread2=CreateThread(NULL,0,ThreadFun2,NULL, 0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
/*while(index++<1000)
cout<<"Main Thread is running\n";*/
hMutex=CreateMutex(NULL,FALSE,NULL);
Sleep(4000);
//Sleep(10);
}
DWORD WINAPI ThreadFun1(
_In_ LPVOID lpParameter
)
{
/*while(index++<1000)
cout<<"Thread1 is running\n";*/
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
{
cout<<"Thread1:"<<tickets--<<'\n';
/*puts("Thread1:");
printf("%d",tickets);
tickets--;*/
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI ThreadFun2(
_In_ LPVOID lpParameter
)
{
/*while(index++<1000)
cout<<"Thread1 is running\n";*/
while(TRUE)
{
WaitForSingleObject(hMutex,INFINITE);
if(tickets>0)
cout<<"Thread2:"<<tickets--<<'\n';
/*{
puts("Thread2:");
printf("%d",tickets);
tickets--;
}*/
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
控制台结果图片:
#define numPerLine 5
//......
cout<<"Thread1:"<<tickets-- << ' ';
if(tickets % numPerLine == 0)
{
cout << endl;
}
.//......