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

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

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

2020-05-23 14:20:23
字體:
供稿:網(wǎng)友
這篇文章主要介紹了C++使用CriticalSection實(shí)現(xiàn)線程同步實(shí)例,是使用CriticalSection對前文實(shí)例的擴(kuò)展,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
 
 

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

具體代碼如下:

  1. #include "stdafx.h"  
  2. #include <Windows.h>  
  3.    
  4. DWORD g_cnt1;  
  5. DWORD g_cnt2;  
  6. BOOL g_bContinue = TRUE;  
  7. CRITICAL_SECTION cs;  
  8.    
  9. DWORD WINAPI ThreadProc(__in LPVOID lpParameter)  
  10. {  
  11.   ::EnterCriticalSection(&cs);  
  12.   while(g_bContinue)  
  13.   {  
  14.     g_cnt1++;  
  15.     g_cnt2++;  
  16.   }  
  17.   ::LeaveCriticalSection(&cs);  
  18.   return 0;  
  19. }  
  20.    
  21. int _tmain(int argc, _TCHAR* argv[])  
  22. {  
  23.   HANDLE hThread[2];  
  24.   g_cnt1 = g_cnt2 = 0;  
  25.   ::InitializeCriticalSection(&cs);  
  26.    
  27.   hThread[0] = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);  
  28.   hThread[1] = ::CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);  
  29.    
  30.   Sleep(1000);  
  31.   g_bContinue = FALSE;  
  32.   ::WaitForMultipleObjects(2, hThread, TRUE, INFINITE);  
  33.   printf("g_cnt1=%d/n",g_cnt1);  
  34.   printf("g_cnt2=%d/n",g_cnt2);  
  35.    
  36.   ::DeleteCriticalSection(&cs);  
  37.    
  38.   ::CloseHandle(hThread[0]);  
  39.   ::CloseHandle(hThread[1]);  
  40.   return 0;  



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


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 天等县| 彭泽县| 汾阳市| 金川县| 罗甸县| 青阳县| 沂水县| 乌恰县| 阳新县| 南昌市| 田东县| 阿鲁科尔沁旗| 孟津县| 齐齐哈尔市| 洞头县| 九江市| 张家港市| 合山市| 南平市| 蓝山县| 镶黄旗| 宿州市| 棋牌| 延寿县| 乐东| 绍兴县| 沾化县| 贵定县| 汉中市| 扎鲁特旗| 蓝山县| 东丰县| 简阳市| 茶陵县| 积石山| 津南区| 迭部县| 荣成市| 当涂县| 游戏| 兴隆县|