线程同步
#include
#include
#include
#include
using namespace std;
int counter = 0;
CRITICAL_SECTION g_cs;
void doit(void* arg)
{
int i, val = 0;
EnterCriticalSection (&g_cs);
for (i=0; i<5; i++)
{
val = counter;
printf("thread %d : %d\n", (int*)arg, val+1);
counter = val + 1;
}
LeaveCriticalSection(&g_cs);
}
int main(int argc, char*argv[])
{
InitializeCriticalSection(&g_cs);
HANDLE hThread1 = CreateThread(nullptr,0, (LPTHREAD_START_ROUTINE)doit, (void*)1, 0, nullptr);
HANDLE hTrehad2 = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)doit, (void*)2, 0, nullptr);
WaitForSingleObject(hThread1, 10*1000);
WaitForSingleObject(hTrehad2, 3*1000);
DeleteCriticalSection(&g_cs);
return 0;
}