国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++使用CriticalSection實(shí)現(xiàn)線程同步實(shí)例

2020-01-26 15:15:08
字體:
供稿:網(wǎng)友

本文實(shí)例講述了C++使用CriticalSection實(shí)現(xiàn)線程同步的方法,在前文C++線程同步實(shí)例分析的基礎(chǔ)上增加了四行代碼,使用了四個函數(shù):
EnterCriticalSection ::DeleteCriticalSection ::EnterCriticalSection ::LeaveCriticalSection此時,打印出來的數(shù)字就相等了。

具體代碼如下:

#include "stdafx.h" #include <Windows.h>  DWORD g_cnt1; DWORD g_cnt2; BOOL g_bContinue = TRUE; CRITICAL_SECTION cs;  DWORD WINAPI ThreadProc(__in LPVOID lpParameter) {   ::EnterCriticalSection(&cs);   while(g_bContinue)   {     g_cnt1++;     g_cnt2++;   }   ::LeaveCriticalSection(&cs);   return 0; }  int _tmain(int argc, _TCHAR* argv[]) {   HANDLE hThread[2];   g_cnt1 = g_cnt2 = 0;   ::InitializeCriticalSection(&cs);    hThread[0] = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);   hThread[1] = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);    Sleep(1000);   g_bContinue = FALSE;   ::WaitForMultipleObjects(2, hThread, TRUE, INFINITE);   printf("g_cnt1=%d/n",g_cnt1);   printf("g_cnt2=%d/n",g_cnt2);    ::DeleteCriticalSection(&cs);    ::CloseHandle(hThread[0]);   ::CloseHandle(hThread[1]);   return 0; }

希望本文所述對大家的C++程序設(shè)計(jì)有所幫助。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 漳州市| 宜都市| 赫章县| 韩城市| 萝北县| 塔河县| 兰溪市| 囊谦县| 泰来县| 万州区| 镇康县| 资阳市| 汉沽区| 沅陵县| 定远县| 淳安县| 平乡县| 礼泉县| 友谊县| 广元市| 海伦市| 从江县| 秭归县| 西林县| 鸡西市| 肇东市| 德江县| 平安县| 东宁县| 康保县| 沾益县| 华容县| 建始县| 靖西县| 建宁县| 乐至县| 西充县| 博客| 合肥市| 灵山县| 蓝山县|