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.

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

  • 相关阅读:
    <trim>: prefix+prefixOverrides+suffix+suffixOverrides
    时间js
    form表单中name和id区别
    SQL 递归
    表单中Readonly和Disabled的区别
    jquery select取值,赋值操作
    ie11
    mongodb 学习资料
    H5 限制input只能输入数字
    http头部解释
  • 原文地址:https://www.cnblogs.com/a-s-m/p/12350204.html
Copyright © 2011-2022 走看看