正文

C/C++中的多线程入门(zt)

(2004-11-01 13:44:34) 下一个

#include <Windows.h>
#include <stdio.h>
#include <process.h>

#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 ;
}

[ 打印 ]
[ 编辑 ]
[ 删除 ]
阅读 ()评论 (1)
评论
目前还没有任何评论
登录后才可评论.