zoukankan      html  css  js  c++  java
  • 使用临界区 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)等等。

  • 相关阅读:
    Thinkcmf:页面常用函数
    thinkcmf开发--关于控制器
    thinkcmf 常用操作
    Thinkcmf 二次开发
    Sublime Text 3 快捷键精华版
    php动态更改post_max_size, upload_max_filesize等值
    Jquery使用小技巧
    jQuery常用方法和函数
    三层架构
    JDBC
  • 原文地址:https://www.cnblogs.com/cxun/p/1680424.html
Copyright © 2011-2022 走看看