一个简单的多线程例子-临界区

来源:互联网 发布:iphone软件更新小红点 编辑:程序博客网 时间:2024/06/08 06:39
// Critical.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <windows.h>#include <iostream>using namespace std;static int nGloble = 0;CRITICAL_SECTION gcs;DWORD WINAPI RecvThread(LPVOID lp){int num = *(DWORD*)lp;while (nGloble < 1000){printf("Thread %d nGloble = %d\n", num, nGloble);EnterCriticalSection(&gcs);nGloble++;LeaveCriticalSection(&gcs);}return 0;}int _tmain(int argc, _TCHAR* argv[]){InitializeCriticalSection(&gcs);HANDLE Thread[10];for(int i=0; i<10; i++){Thread[i] = CreateThread(NULL, 0, RecvThread, &i, 0, NULL);Sleep(500);}WaitForMultipleObjects(10, Thread, TRUE, 100000);DeleteCriticalSection(&gcs);CloseHandle(Thread);return 0;}

原创粉丝点击