关键段使线程访问共享资源之前独占它,共享资源访问结束后线程释放对资源的独占。但是这个过程中,系统也可能暂停该线程取调度其他线程,但是,在关键段释放之前,不会调度其他想访问同一资源的线程。
#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;
int g_x = 0;
//把CRITICAL_SECTION定义成全局变量,以使所有的线程都能方便快速访问
CRITICAL_SECTION g_cs;
UINT WINAPI ThreadFunc1(PVOID pArguments)
{
// EnterCriticalSection和LeaveCriticalSection把共享资源包起来
EnterCriticalSection(&g_cs);
cout << "ThreadFunc1.." << endl;
int n = 0;
while (n < 3)
{
g_x += n;
n++;
}
LeaveCriticalSection(&g_cs);
_endthreadex(0);
return 0;
}
UINT WINAPI ThreadFunc2(PVOID pArguments)
{
EnterCriticalSection(&g_cs);
cout << "ThreadFunc2.." << endl;
int n = 0;
while (n < 5)
{
g_x += n;
n++;
}
LeaveCriticalSection(&g_cs);
_endthreadex(0);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handle1, handle2;
unsigned unThread1ID, unThread2ID;
cout << "g_x initial value: " << g_x << endl;
//必须初始化CRITICAL_SECTION成员
InitializeCriticalSection(&g_cs);
handle1 = (HANDLE)_beginthreadex(NULL,
0,
&ThreadFunc1,
NULL,
0,
&unThread1ID);
handle2 = (HANDLE)_beginthreadex(NULL,
0,
&ThreadFunc2,
NULL,
0,
&unThread2ID);
WaitForSingleObject(handle1, INFINITE);
WaitForSingleObject(handle2, INFINITE);
cout << "g_x Final value: " << g_x << endl;
//清理CRITICAL_SECTION成员
DeleteCriticalSection(&g_cs);
getchar();
return 0;
}
有点: 容易使用,并且内部使用了Interlocked函数,因此执行速度非常快。
缺点: 不能在多个进程之间对线程同步