作者: 贺忆东
一个很简单的多线程程序,主要用于了解临界区的使用
#include
#include
#include
#pragma comment(lib,"libcmt.lib")
const int NLOOP = 100;
int counter = 0;
void doit(void*);
CRITICAL_SECTION beswap ;
int main()
{
HANDLE pnt[2];
InitializeCriticalSection(&beswap);
pnt[0] = (HANDLE)_beginthread(doit,0,NULL);
pnt[1] = (HANDLE)_beginthread(doit,0,NULL);
WaitForMultipleObjects( 2, pnt, TRUE, 1000L);
DeleteCriticalSection(&beswap);
return 0;
}
void doit(void*)
{
printf("go...\n");
int i, val = 0;
for(i = 0; i < NLOOP; ++i)
{
EnterCriticalSection(&beswap);
val = counter;
printf("%d\n",val+1);
counter = val + 1;
LeaveCriticalSection(&beswap);
}
printf("end...\n");
return ;
}