zoukankan      html  css  js  c++  java
  • 线程安全-互斥体

    内核版的令牌

     相关函数

    HANDLE CreateMutexA(
      LPSECURITY_ATTRIBUTES lpMutexAttributes,
      BOOL                  bInitialOwner,//FALSE的时候,互斥体创建出来就可以用
      LPCSTR                lpName
    );

    示例代码,下面是两个程序,代表两个进程,两个进程中抢同一个内核令牌

    //A进程代码
    int main()
    {
        //创建令牌
        HANDLE g_mutex = CreateMutex(NULL,FALSE,"HEHE");
        //获取令牌
        WaitForSingleObject(g_mutex,INFINITE);
        for(int i=0;i<10;i++)
        {
            Sleep(5000);
            printf("这是A进程。。。。%d
    ",i);
        }
        //释放令牌
        ReleaseMutex(g_mutex);
        return 0;
    }
    
    //B进程代码
    int main()
    {
        //创建令牌
        HANDLE g_mutex = CreateMutex(NULL,FALSE,"HEHE");
        //获取令牌
        WaitForSingleObject(g_mutex,INFINITE);
        for(int i=0;i<10;i++)
        {
            Sleep(5000);
            printf("这是B进程。。。。%d
    ",i);
        }
        //释放令牌
        ReleaseMutex(g_mutex);
        return 0;
    }

    对于CreateMutex函数的官方说明

    If the function succeeds, the return value is a handle to the newly created mutex object.
    If the function fails, the return value is NULL. To get extended error information, call GetLastError.
    If the mutex is a named mutex and the object existed before this function call, 
    the return value is a handle to the existing object, OpenMutexa> function.

    可以实现一个程序只运行一份(单开)

  • 相关阅读:
    单行居中,2行居左,超过2行省略
    Angular2环境搭建
    数字保留2位小数
    结束循环函数
    获取元素的定位值
    $.extend
    node使用指南
    Telsa显卡比较
    Jupyter-notebook 不自动打开浏览器解决办法
    teamviewer连接未就绪的解决(Manjaro Linux)
  • 原文地址:https://www.cnblogs.com/a-s-m/p/12350204.html
Copyright © 2011-2022 走看看