使用临界区 CRITICAL_SECTION 实现互斥
下面是使用 CRITICAL_SECTION 實(shí)現(xiàn)互斥的例子:
?
#include <windows.h>
#include <iostream>
using namespace std;
//#define USE_CRITICAL_SECTION
CRITICAL_SECTION g_cs;
DWORD WINAPI thread(PVOID pBuf)
{
#ifdef USE_CRITICAL_SECTION
??? EnterCriticalSection(&g_cs);
#endif
??? LARGE_INTEGER li;
??? QueryPerformanceCounter(&li);
??? srand(li.QuadPart);
??? int time = rand() % 1000;
??? cout<<"Sleep time: "<<time<<" ms"<<endl;
??? Sleep(time);
??? cout<<"This is "<<(char*)pBuf<<endl;
#ifdef USE_CRITICAL_SECTION
??? LeaveCriticalSection(&g_cs);
#endif
??? return 0;
}
void main()
{
#ifdef USE_CRITICAL_SECTION
??? InitializeCriticalSection(&g_cs);
#endif
??? CreateThread(0, 0, &thread, "thread 1", 0, 0);
??? CreateThread(0, 0, &thread, "thread 2", 0, 0);
??? Sleep(2100);
}
?
除了使用臨界區(qū)(CRITICAL_SECTION)外,還有其它方法,如互斥(mutex)、事件(event)等等。
總結(jié)
以上是生活随笔為你收集整理的使用临界区 CRITICAL_SECTION 实现互斥的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: window.showModalDial
- 下一篇: 女性养生需知的16条健康戒律