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.

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

  • 相关阅读:
    CALayer3-层的属性
    CALayer2-创建新的层
    CALayer1-简介
    autofac 使用
    .net5的异步
    动态添加菜单
    PDF解析帮助类
    正则获取字符串中两个字符串间的内容
    水晶报表
    通用easyui查询页面组件
  • 原文地址:https://www.cnblogs.com/a-s-m/p/12350204.html
Copyright © 2011-2022 走看看