当前位置:编程学习 > VC++ >>

多线程编程示例

#include "stdafx.h"
#include <windows.h>
#define THREAD_NUM 50 //线程数
CRITICAL_SECTION g_cs;
int ThreadProc(LPVOID lpParam)
{
 int x = *(int*)lpParam;
 for (int i=0; i<5; i++)
 {
  EnterCriticalSection(&g_cs);
  printf("[%d]:%d\n",x,i);
  LeaveCriticalSection(&g_cs);
 }
 return x;
}
int _tmain(int argc, _TCHAR* argv[])
{
 InitializeCriticalSection(&g_cs);
 HANDLE hThread[THREAD_NUM];
 int nValue[THREAD_NUM];
 for (int i=0; i<THREAD_NUM; i++)
 {
  nValue[i] = i;
  hThread[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProc,(LPVOID)&nValue[i],0,NULL);
 }
 WaitForMultipleObjects(THREAD_NUM,hThread,TRUE,INFINITE); //等待所有线程执行完毕
 DWORD dwCode = 0;
 for (int i=0; i<THREAD_NUM; i++)
 {
  if (GetExitCodeThread(hThread[i],&dwCode)) //获取各个线程的返回值
   printf("%d\n",dwCode);
  CloseHandle(hThread[i]);
 }
 DeleteCriticalSection(&g_cs);
 return 0;
}
 
补充:软件开发 , Vc ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,