互斥量(Mutex)

CreateMutex :创建一个互斥量

HANDLE   CreateMutex(  
          LPSECURITY_ATTRIBUTES   lpMutexAttributes, //   pointer   to   security   attributes    
          BOOL   bInitialOwner, //   flag   for   initial   ownership    
          LPCTSTR   lpName   //   pointer   to   mutex-object   name      
        );

Parameters
   
    lpMutexAttributes [in, optional]
   
        A pointer to a SECURITY_ATTRIBUTES structure. If this parameter is NULL, the handle cannot be inherited by child processes.
   
        The lpSecurityDescriptor member of the structure specifies a security descriptor for the new mutex. If lpMutexAttributes is NULL, the mutex gets a default security descriptor. The ACLs in the default security descriptor for a mutex come from the primary or impersonation token of the creator. For more information, see Synchronization Object Security and Access Rights.

bInitialOwner [in]
   
        If this value is TRUE and the caller created the mutex, the calling thread obtains initial ownership of the mutex object. Otherwise, the calling thread does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.

lpName [in, optional]
   
        The name of the mutex object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.
   
        If lpName matches the name of an existing named mutex object, this function requests the MUTEX_ALL_ACCESS access right. In this case, the bInitialOwner parameter is ignored because it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.
   
        If lpName is NULL, the mutex object is created without a name.
   
        If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space.
   
        The name can have a "Global/" or "Local/" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (/). For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.
   
            Windows 2000:  If Terminal Services is not running, the "Global/" and "Local/" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
   
        The object can be created in a private namespace. For more information, see Object Namespaces.
   
    Return Value
   
    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, GetLastError returns ERROR_ALREADY_EXISTS, bInitialOwner is ignored, and the calling thread is not granted ownership. However, if the caller has limited access rights, the function will fail with ERROR_ACCESS_DENIED and the caller should use the OpenMutex function.

OpenMutex :为现有的一个已命名互斥量创建一个新句柄

HANDLE WINAPI OpenMutex(
      __in  DWORD dwDesiredAccess,
      __in  BOOL bInheritHandle,
      __in  LPCTSTR lpName
    );

Parameters
   
    dwDesiredAccess [in]
   
        The access to the mutex object. Only the SYNCHRONIZE access right is required to use a mutex; to change the mutex's security, specify MUTEX_ALL_ACCESS. The function fails if the security descriptor of the specified object does not permit the requested access for the calling process. For a list of access rights, see Synchronization Objec t Security and Access Rights.

bInheritHandle [in]
   
        If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle.

lpName [in]
   
        The name of the mutex to be opened. Name comparisons are case sensitive.
   
        This function can open objects in a private namespace. For more information, see Object Namespaces.
   
            Terminal Services:  The name can have a "Global/" or "Local/" prefix to explicitly open an object in the global or session name space. The remainder of the name can contain any character except the backslash character (/). For more information, see Kernel Object Namespaces.
   
            Windows XP Home Edition:  Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.
   
            Windows 2000:  If Terminal Services is not running, the "Global/" and "Local/" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
   
    Return Value
   
    If the function succeeds, the return value is a handle to the mutex object.
   
    If the function fails, the return value is NULL. To get extended error information, call GetLastError.
   
    If a named mutex does not exist, the function fails and GetLastError returns ERROR_FILE_NOT_FOUND.

CloseHandle :关闭句柄

BOOL WINAPI CloseHandle(
      __in  HANDLE hObject
    );

Parameters
   
    hObject [in]
   
        A valid handle to an open object.
   
    Return Value
   
    If the function succeeds, the return value is nonzero.
   
    If the function fails, the return value is zero. To get extended error information, call GetLastError.
   
    If the application is running under a debugger, the function will throw an exception if it receives either a handle value that is not valid or a pseudo-handle value. This can happen if you close a handle twice, or if you call CloseHandle on a handle returned by the FindFirstFile function instead of calling the FindClose function.

事件(Event)

CreateEvent :创建一个事件对象.

HANDLE WINAPI CreateEvent(
      __in_opt  LPSECURITY_ATTRIBUTES lpEventAttributes,
      __in      BOOL bManualReset,
      __in      BOOL bInitialState,
      __in_opt  LPCTSTR lpName
    );

Parameters
   
    lpEventAttributes [in, optional]
   
        A pointer to a SECURITY_ATTRIBUTES structure. If this parameter is NULL, the handle cannot be inherited by child processes.
   
        The lpSecurityDescriptor member of the structure specifies a security descriptor for the new event. If lpEventAttributes is NULL, the event gets a default security descriptor. The ACLs in the default security descriptor for an event come from the primary or impersonation token of the creator.
    bManualReset [in]
   
        If this parameter is TRUE, the function creates a manual-reset event object, which requires the use of the ResetEvent function to set the event state to nonsignaled. If this parameter is FALSE, the function creates an auto-reset event object, and system automatically resets the event state to nonsignaled after a single waiting thread has been released.
    bInitialState [in]
   
        If this parameter is TRUE, the initial state of the event object is signaled; otherwise, it is nonsignaled.
    lpName [in, optional]
   
        The name of the event object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.
   
        If lpName matches the name of an existing named event object, this function requests the EVENT_ALL_ACCESS access right. In this case, the bManualReset and bInitialState parameters are ignored because they have already been set by the creating process. If the lpEventAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.
   
        If lpName is NULL, the event object is created without a name.
   
        If lpName matches the name of another kind of object in the same name space (such as an existing semaphore, mutex, waitable timer, job, or file-mapping object), the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This occurs because these objects share the same name space.
   
        The name can have a "Global/" or "Local/" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash character (/). For more information, see Kernel Object Namespaces. Fast user switching is implemented using Terminal Services sessions. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.
   
            Windows 2000:   If Terminal Services is not running, the "Global/" and "Local/" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
   
        The object can be created in a private namespace. For more information, see Object Namespaces.
   
    Return Value
   
    If the function succeeds, the return value is a handle to the event object. If the named event object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS.
   
    If the function fails, the return value is NULL. To get extended error information, call GetLastError.

openevent :为现有的一个已命名事件对象创建一个新句柄

HANDLE WINAPI OpenEvent(
      __in  DWORD dwDesiredAccess,
      __in  BOOL bInheritHandle,
      __in  LPCTSTR lpName
    );

Parameters
   
    dwDesiredAccess [in]
   
        The access to the event object. The function fails if the security descriptor of the specified object does not permit the requested access for the calling process. For a list of access rights, see Synchronization Object Security and Access Rights.
    bInheritHandle [in]
   
        If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle.
    lpName [in]
   
        The name of the event to be opened. Name comparisons are case sensitive.
   
        This function can open objects in a private namespace. For more information, see Object Namespaces.
   
            Terminal Services:  The name can have a "Global/" or "Local/" prefix to explicitly open an object in the global or session name space. The remainder of the name can contain any character except the backslash character (/). For more information, see Kernel Object Namespaces.
   
            Windows XP Home Edition:  Fast user switching is implemented using Terminal Services sessions. The first user to log on uses session 0, the next user to log on uses session 1, and so on. Kernel object names must follow the guidelines outlined for Terminal Services so that applications can support multiple users.
   
            Windows 2000:  If Terminal Services is not running, the "Global/" and "Local/" prefixes are ignored. The remainder of the name can contain any character except the backslash character.
   
    Return Value
   
    If the function succeeds, the return value is a handle to the event object.
   
    If the function fails, the return value is NULL. To get extended error information, call GetLastError.

事件(event)与互斥量(mutex)区别

事件(event)
    事件是用来同步地位不相等的线程的,事件可以用来使一个线程完成一件事情,然后另外的线程完成剩下的事情。事件的使用很灵活,自动 事件的激发态是由人工来控制的,而Mutex在释放(releaseMetux)后就一直处于激发态,直到线程WaitForSingleObject。 事件可以用来控制经典的读写模型和生产者和消费者模型。相应的方式为,生成者等待消费者的消费,再消费者消费完后通知生产者进行生产。
互斥量(Mutex)
    Mutex 是排他的占有资源,一般用于地位相等的现在进行同步,每个线程都可以排他的访问一个资源或代码段,不存在哪个线程对资源访问存在优先次序。一个线程只能在 Mutex处于激发态的时候访问被保护的资源或代码段,线程可以通过WaitForSingelObject来等待Mutex,在访问资源完成之 后,ReleaseMutex释放Mutex,此时Mutex处于激发态。Mutex具有成功等待的副作用,在等待到Mutex后,Mutex自动变为未 激发态,直到调用ReleaseMutex使Mutex变为激发态为止。自动事件也具有成功等待的副作用。手动事件没有,必须ResetEvent使手动 事件变为未激发态。进程和线程也没有成功等待的副作用。当线程或者进程函数返回时,线程内核对象变为激发态,但WaitForSingleObject并 没有使线程或者进程的内核对象变为未激发态。
总之,事件一般用于控制线程的先后顺序,而Mutex一般用于排他的访问资源。

Mutex示例:

//A   consule   application 
    CWinApp   theApp; 
    int   iCounter=0; 
    DWORD   threadA(void*   pD) 
    { 
        int   iID=(int)pD; 
        //在内部重新打开 
        HANDLE   hCounterIn=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"sam   sp   44"); 
        for(int   i=0;i<3;i++) 
        { 
            printf("%d   wait   for   object/n",iID); 
            WaitForSingleObject(hCounterIn,INFINITE); 
            int   iCopy=iCounter; 
            Sleep(500*iID); 
            iCounter=iCopy+1; 
            printf("/t/tthread   %d   :   %d/n",iID,iCounter); 
            ReleaseMutex(hCounterIn); 
        } 
        CloseHandle(hCounterIn); 
        return   0; 
    }

using   namespace   std; 
    int _tmain(int   argc,   TCHAR*   argv[],   TCHAR*   envp[]) 
    { 
        int   nRetCode   =   0; 
        //   initialize   MFC   and   print   and   error   on   failure 
        if   (!AfxWinInit(::GetModuleHandle(NULL),   NULL,   ::GetCommandLine(),   0)) 
        { 
            //   TODO:   change   error   code   to   suit   your   needs 
            cerr   <<   _T("Fatal   Error:   MFC   initialization   failed")   <<   endl; 
            nRetCode   =   1; 
        } 
        else 
        { 
            //   TODO:   code   your   application's   behavior   here. 
            //创建互斥量 
            HANDLE   hCounter=NULL; 
            if(   (hCounter=OpenMutex(MUTEX_ALL_ACCESS,FALSE,"sam   sp   44"))==NULL) 
            { 
            //如果没有其他进程创建这个互斥量,则重新创建 
            hCounter   =   CreateMutex(NULL,FALSE,"sam   sp   44"); 
            } 
            //创建线程 
            HANDLE   hThread[4]; 
            CWinThread*   pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1); 
            CWinThread*   pT2=AfxBeginThread((AFX_THREADPROC)threadA,(void*)2); 
            CWinThread*   pT3=AfxBeginThread((AFX_THREADPROC)threadA,(void*)3); 
            CWinThread*   pT4=AfxBeginThread((AFX_THREADPROC)threadA,(void*)4); 
            hThread[0]=pT1->m_hThread; 
            hThread[1]=pT2->m_hThread; 
            hThread[2]=pT3->m_hThread; 
            hThread[3]=pT4->m_hThread; 
            //等待线程结束 
            WaitForMultipleObjects(4,hThread,TRUE,INFINITE);//5000);// 
            cout<<"over!"<<endl; 
            //关闭句柄 
            CloseHandle(hCounter); 
        } 
        return   nRetCode; 
    }

互斥量(mutex)与事件(event)的使用相关推荐

  1. mysql 互斥_MySql中互斥量mutex的实现

    数据库中的Mutex量指的是一种用于保护一些临界资源的使用的信号量.当有线程需要使用这些临界资源时,会请求获得mutex量,请求成功的线程进入临界区,而请求失败的线程只能等待它释放这个mutex.互斥 ...

  2. [一个经典的多线程同步问题]解决方案三:互斥量Mutex

    本篇通过互斥量来解决线程的同步,学习其中的一些知识. 互斥量也是一个内核对象,它用来确保一个线程独占一个资源的访问.互斥量与关键段的行为非常相似,并且互斥量可以用于不同进程中的线程互斥访问资源.使用互 ...

  3. 秒杀多线程第七篇 经典线程同步 互斥量Mutex

    阅读本篇之前推荐阅读以下姊妹篇: <秒杀多线程第四篇一个经典的多线程同步问题> <秒杀多线程第五篇经典线程同步关键段CS> <秒杀多线程第六篇经典线程同步事件Event& ...

  4. 经典线程同步 互斥量Mutex的使用分析

    互斥量(mutex)内核对象用来确保一个线程独占对一个资源的访问. 互斥量对象包含一个使用计数.线程ID以及一个递归计数. 互斥量与关键段的行为完全相同.但是,互斥量是内核对象,而关键段是用户模式下的 ...

  5. windows 多线程(五) 互斥量(Mutex)

    参考:http://blog.csdn.net/morewindows/article/details/7470936 互斥量也是一个内核对象,它用来确保一个线程独占一个资源的访问.互斥量与关键段的行 ...

  6. Linux系统编程----16(线程同步,互斥量 mutex,互斥锁的相关函数,死锁,读写锁)

    同步概念 所谓同步,即同时起步,协调一致.不同的对象,对"同步"的理解方式略有不同.如,设备同步,是指在两 个设备之间规定一个共同的时间参考:数据库同步,是指让两个或多个数据库内容 ...

  7. linux mutex 数量上限,互斥量mutex

    Linux中提供一把互斥锁mutex(也称之为互斥量). 每个线程在对资源操作前都尝试先加锁,成功加锁才能操作,操作结束解锁. 资源还是共享的,线程间也还是竞争的,但通过"锁"就将 ...

  8. C#线程同步(3)- 互斥量 Mutex

    什么是Mutex "mutex"是术语"互相排斥(mutually exclusive)"的简写形式,也就是互斥量.互斥量跟临界区中提到的Monitor很相似, ...

  9. C# 多线程四:互斥量Mutex的简单理解与运用

    目录 一. 特点: 1.非静态类继承 2.可以跨进程 二.构造函数 1.Mutex() 2.Mutex(Boolean) 2. Mutex(Boolean, String) 3.Mutex(Boole ...

最新文章

  1. (转)uml 静态视图依赖
  2. 枚举 + 进制转换 --- hdu 4937 Lucky Number
  3. koa2 mysql 中间件_Koa2第二篇:中间件
  4. 轻松理解—继承成员访问控制机制
  5. LeetCode 1191. K 次串联后最大子数组之和(前缀和+分类讨论)
  6. python有什么内容_python能做什么
  7. 带你一文搞懂网络层的IP协议\数据链路层的以太网\ARP协议以及DNS和NAT协议
  8. Win32 Application和Win32 Console Application区别
  9. N1刷Android TV,贫民种草指北 篇二:N1盒子:不谈刷机,只谈使用!
  10. 10月书讯(上) | 小长假我读这些新书
  11. R语言实现随机分组(按照学号或者是姓名随机分组)
  12. 树莓派CM4和CM4IO上手
  13. display的contents属性
  14. Oracle OCA、OCP、OCM认证科目及考试内容
  15. npm cb() never called!和 Error: getaddrinfo ENOTFOUND registry.npmjs.com registry.npmjs.com:443
  16. matlab采样率为100hz,matlab自己设计一个低通滤波器,要求滤出100Hz之外的频率,采样率为10000Hz...
  17. docker中php环境慢,解决访问本地 docker 项目慢的问题
  18. ksoftirqid进程CPU100%排查
  19. Fater RCNN 试着加入注意力机制模型
  20. 前端怎么画三角形_css画出三角形和梯形

热门文章

  1. 游戏夜读 | 写游戏用什么语言?
  2. 计算机系迎新晚会策划,学院迎新晚会活动方案
  3. MLDonkey,比aMule好的BT软件
  4. IT职业教育(3)IT教育的商道
  5. 编程之美 - 烙饼问题
  6. 爬取三联生活周刊新闻(进阶版)
  7. 机器学习7 - 算法进阶2
  8. Java学习基础(二)
  9. dbase_create、dbase使用小结
  10. 查询局域网电脑的IP,端口号,MAC地址 黑客技术入门