亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C++線程同步實(shí)例分析

 更新時(shí)間:2014年10月10日 09:42:56   投稿:shichen2014  
這篇文章主要介紹了C++線程同步實(shí)例分析,以實(shí)例的形式較為深入的分析了C++的線程同步問(wèn)題,是一個(gè)較為經(jīng)典的線程同步問(wèn)題,需要的朋友可以參考下

本文實(shí)例分析了C++線程同步問(wèn)題,分享給大家供大家參考。具體分析如下:

該實(shí)例設(shè)置全局變量g_bContinue,在主線程中設(shè)置全局變量g_bContinue,工作線程檢測(cè)該全局變量,實(shí)現(xiàn)主線程控制工作線程的目的。

打印出的g_cnt1與g_cnt2的數(shù)值不同,是因?yàn)榫€程調(diào)試時(shí)時(shí)間片的切換。

具體代碼如下:

// countError.cpp : 定義控制臺(tái)應(yīng)用程序的入口點(diǎn)。 
// 
#include "stdafx.h" 
#include <Windows.h> 
 
DWORD g_cnt1; 
DWORD g_cnt2; 
BOOL g_bContinue = TRUE; 
DWORD WINAPI ThreadProc(__in LPVOID lpParameter) 
{ 
  while(g_bContinue) 
  { 
    g_cnt1++; 
    g_cnt2++; 
  } 
  return 0; 
} 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
  HANDLE hThread[2]; 
  g_cnt1 = g_cnt2 = 0; 
 
  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); 
  ::CloseHandle(hThread[0]); 
  ::CloseHandle(hThread[1]); 
  return 0; 
}

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

相關(guān)文章

最新評(píng)論