C/C++全局变量多线程并发访问临界锁(Critical Section Lock)
因为之前一直习惯于C语言编程,对C++的一些使用方式没有在意过,在阅读一些代码后渐渐的发现了C++的一些便捷性,这种便捷性在一定程度上降低了我们的编码量,对于全局变量多线程并发访问一般可以通过临界区(Critical Section)实现,比如在C语言中形如以下代码:
#include <windows.h>
#define THREAD_NUM 5
CRITICAL_SECTION g_cs;
int g_nResource;
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
EnterCriticalSection(&g_cs);
printf("Thread id %d Resource Count %d\n",
GetCurrentThreadId(), g_nResource);
g_nResource++;
LeaveCriticalSection(&g_cs);
return 0;
}
int main(void)
{
HANDLE hThreads[THREAD_NUM] = {0};
InitializeCriticalSection(&g_cs);
for (i = 0; i < THREAD_NUM; i++)
hThreads[i] = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
WaitForMultipleObjects(THREAD_NUM, hThreads, TRUE, INFINITE);
DeleteCriticalSection(&g_cs);
return 0;
}