#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;
static int g_iCnt = 100;
CRITICAL_SECTION g_CriticalSection;
DWORD WINAPI Thread1(LPVOID lpParmeter);
DWORD WINAPI Thread2(LPVOID lpParmeter);
int main()
{
HANDLE hThread1 ;
HANDLE hThread2 ;
InitializeCriticalSection(&g_CriticalSection);
hThread1 = CreateThread(NULL, 0, Thread1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Thread2, NULL, 0, NULL);
HANDLE h[2]={hThread1,hThread2};
//等待线程退出
DWORD ret = WaitForMultipleObjects(2,h,TRUE,INFINITE);
switch(ret)
{
case WAIT_TIMEOUT:
cout<<"WAIT_TIMEOUT"<<endl;
break;
case WAIT_FAILED:
cout<<"WAIT_FAILED"<<endl;
break;
default:
cout<<"Success!"<<endl;
break;
}
CloseHandle(hThread1);
CloseHandle(hThread2);
DeleteCriticalSection(&g_CriticalSection); // 删除
system("PAUSE");
return 0;
}
DWORD WINAPI Thread1(LPVOID lpParmeter)
{
int t = 100;
while (t > 0)
{
//进入临界区,获得所有权,其他线程就等
EnterCriticalSection(&g_CriticalSection);
t = g_iCnt ; //这才是临界区里面应该做的事情。
if (t > 0)
{
cout << "Thread1:" << g_iCnt-- << endl;
}
LeaveCriticalSection(&g_CriticalSection);
Sleep(20); //不能在临界区里等待
}
return 0;
}
DWORD WINAPI Thread2(LPVOID lpParameter)//thread data
{
int t = 100;
while (t > 0)
{
EnterCriticalSection(&g_CriticalSection);
t = g_iCnt;
if (t > 0)
{
cout << "thread2:" << g_iCnt-- << endl;
}
LeaveCriticalSection(&g_CriticalSection);
Sleep(20);
}
return 0;
}
多线程编程
最新推荐文章于 2025-01-08 00:34:48 发布