使用临界区 CRITICAL_SECTION 实现互斥

下面是使用 CRITICAL_SECTION 实现互斥的例子:

 

#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);
}

 

除了使用临界区(CRITICAL_SECTION)外,还有其它方法,如互斥(mutex)、事件(event)等等。

posted @ 2010-03-07 22:44  cxun  阅读(2484)  评论(0编辑  收藏  举报