最近一段時期準(zhǔn)備溫習(xí)多線程同步相關(guān)內(nèi)容,主要包括關(guān)鍵代碼段和各種內(nèi)核同步對象。先學(xué)習(xí)最簡單的同步方法--Critical Section。所謂關(guān)鍵代碼段,是指給一段代碼加上鎖,要執(zhí)行這段代碼,必須拿到一把鑰匙,而且這把鑰匙世界上僅存一把,獨一無二。
如下代碼所示:
CRITICAL_SECTION g_cs;
EnterCriticalSection(&g_cs);
//add your critical code here
....
LeaveCriticalSection(&g_cs);
在執(zhí)行...這段代碼前,必須確保g_cs沒有被其他線程占有,否則線程就在此處掛起。通過這種方式可以保護某個資源,不被多個線程同時訪問。
以下代碼演示了兩個線程在使用Critical Section和不使用的條件下的輸出結(jié)果:
// stdafx.h : 標(biāo)準(zhǔn)系統(tǒng)包含文件的包含文件,
// 或是經(jīng)常使用但不常更改的
// 特定于項目的包含文件
#pragma once
#define WIN32_LEAN_AND_MEAN // 從 Windows 頭中排除極少使用的資料
#include <stdio.h>
#include <tchar.h>
#include <iostream>
// critical_section.cpp : 定義控制臺應(yīng)用程序的入口點。
//
#include "stdafx.h"
#include <Windows.h>
using namespace std;
CRITICAL_SECTION g_cs;
int g_var = 0;
DWORD WINAPI ThreadProc(LPVOID
lpParam)
{
cout
<< "child thread started!\n";
for(int
i=0;i<30;i++)
{
//EnterCriticalSection(&g_cs);
cout
<< "The " << "child ";
cout
<< "thread " << "enter ";
cout
<< "the CS!" << "\n";
g_var++;
cout
<< "g_var added by 1: g_var = " << g_var << endl;
cout
<< "The " << "child " << "thread
" << "leave " << "the CS!" <<
"\n";
//LeaveCriticalSection(&g_cs);
}
cout
<< "child thread ended!\n";
return
0;
}
int _tmain(int argc, _TCHAR*
argv[])
{
cout
<< "main thread started!\n";
InitializeCriticalSection(&g_cs);
DWORD
tid;
HANDLE
hThread = CreateThread(0, 0, ThreadProc, 0, 0, &tid);
for(int
i=0;i<30;i++)
{
//EnterCriticalSection(&g_cs);
cout
<< "The " << "main " << "thread
";
cout
<< "enter " << "the CS!" <<
"\n";
g_var--;
cout
<< "g_var minused by 1: g_var = " << g_var << endl;
cout
<< "The " << "main " << "thread
";
cout
<< "enter " << "the CS! " <<
"\n";
//LeaveCriticalSection(&g_cs);
}
WaitForSingleObject(hThread,
INFINITE);
CloseHandle(hThread);
DeleteCriticalSection(&g_cs);
cout
<< "main thread ended!\n";
return
0;
}
將如下代碼的注釋去掉即變成了使用Critical Section的實例。
//EnterCriticalSection(&g_cs);
//LeaveCriticalSection(&g_cs);
EnterCriticalSection()的缺點是如果g_cs仍未被其他線程釋放,就一直在此處掛起,如果不想線程掛起,可以用替代函數(shù):
BOOL WINAPI TryEnterCriticalSection(
__inout LPCRITICAL_SECTION lpCriticalSection
);
下一章將講述互斥--Mutex的使用。
只有注冊用戶登錄后才能發(fā)表評論。 | ||
【推薦】100%開源!大型工業(yè)跨平臺軟件C++源碼提供,建模,組態(tài)!
![]() |
||
網(wǎng)站導(dǎo)航:
博客園
IT新聞
BlogJava
博問
Chat2DB
管理
|
||
|