发新帖

VC++线程同步之临界区(CriticalSection)

零下一度 2022-11-30 721

1、相关文件和接口

CRITICAL_SECTION cs;//定义临界区对象
InitializeCriticalSection(&cs);//初始化临界区
EnterCriticalSection(&cs);//进入临界区
LeaveCriticalSection(&cs);//离开临界区
DeleteCriticalSection(&cs);//删除临界区

2、测试代码

#include <Windows.h>
#include <string>
#include <iostream>
CRITICAL_SECTION cs;
DWORD WINAPI Fun(LPVOID lpParamter)
{
    std::string strPrint((const char*)lpParamter);
    int iRunTime = 0;
     while(++iRunTime<10)
     {
         EnterCriticalSection(&cs);
        
         std::cout <<"["<< iRunTime <<"]:"<< strPrint.c_str()<<std::endl;
         LeaveCriticalSection(&cs);
         Sleep(1); //离开临界区后线程进行休眠,其它线程进入临界区的概率大大降低,所以需要短暂休眠。
     }
    
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{    
    InitializeCriticalSection(&cs);
    //创建五个子线程
    std::string str1 = "A";
    std::string str2 = "B";
    std::string str3 = "C";
    std::string str4 = "D";
    std::string str5 = "E";
    HANDLE hThread1 = CreateThread(NULL, 0, Fun, (void*)str1.c_str(), 0, NULL);
    HANDLE hThread2 = CreateThread(NULL, 0, Fun, (void*)str2.c_str(), 0, NULL);
    HANDLE hThread3 = CreateThread(NULL, 0, Fun, (void*)str3.c_str(), 0, NULL);
    HANDLE hThread4 = CreateThread(NULL, 0, Fun, (void*)str4.c_str(), 0, NULL);
    HANDLE hThread5 = CreateThread(NULL, 0, Fun, (void*)str5.c_str(), 0, NULL);
    //关闭线程
    CloseHandle(hThread1);
    CloseHandle(hThread2);
    CloseHandle(hThread3);
    CloseHandle(hThread4);
    CloseHandle(hThread5);
    getchar();
    DeleteCriticalSection(&cs);
    return 0;
}


@博客园


最新回复 (0)
返回
零下一度
主题数
931
帖子数
0
注册排名
1