Windows平台下的进程/线程的同步与互斥
http://blog.csdn.net/bluemood1986/article/details/7221738
http://www.cnblogs.com/vieri122/archive/2009/09/10/1564104.html
http://hi.baidu.com/minyuanyang/blog/item/cd053a735427121d8601b0ba.html
Windows的临界区(CriticalSection)(非系统内核对象)、内核事件(Event)、互斥量(mutex)、信号量(semaphore)都能完线程间的同步和互斥。一般而言,利用互斥量和事件就已经足够解决几乎所有的线程同步问题了
临界区:非内核对象,它只能同步一个进程中的线程,不能跨进程同步;一般用它来做单个进程内的代码块同步,效率较高。相关结构CRITICAL_SECTION _critical
InitializeCriticalSection(& _critical)
EnterCriticalSection(& _critical)
TryEnterCriticalSection(& _critical)
LeaveCriticalSection(& _critical)
DeleteCriticalSection(& _critical)
内核事件:多用于线程间通信,可以跨进程同步,通过CreateEvent创建;相关结构HANDLE hEvent
CreateEvent(NULL,FALSE,FALSE,NULL)
WaitForSingleObject(hEvent,INIFINET)
WaitForMultiObjects(DWORD nCount, CONST HANDLE *lpHandles, BOOLfWaitAll,DWORD dwMilliseconds)
OpenEvent(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCTSTR lpName/*事件对象名*/)//用于跨进程同步
SetEvent(hEvent)
ResetEvent(hEvent)
互斥量:同过创建命名互斥量,可以跨进程同步,还可以用来保证程序只有一个实例运行;相关数据结构HANDLE hMutext
CreateMutex(NULL,FALSE,NULL)
WaitForsingleObject(hMutex,INIFINET)
ReleaseMutex(hMutext,INIFINET)
WaitForMultiObjects(DWORD nCount, CONST HANDLE *lpHandles, BOOLfWaitAll,DWORD dwMilliseconds)
OpenEvent(DWORD dwDesiredAccess, BOOL bInheritHandle, LPCTSTR lpName/*互斥对象名*/)//用于跨进程同步
信号量:可以跨进程同步,它与前几种方式不同,允许多个线程或者进程同时使用共享资源,但是需要限制在同一时刻访问此资源的最大线程数目
CreateSemaphore(NULL, LONG lInitialCount,LONG lMaximumCount, LPCTSTRlpName)
OpenSemaphore(DWORD dwDesiredAccess,BOOL bInheritHandle, LPCTSTR lpName/*信号量对象名*/)//用于跨进程同步
ReleaseSemaphore(HANDLE hSemaphore, LONG lReleaseCount,LPLONGlpPreviousCount)//将信号量加一
WaitForSingleObject(hEvent,INIFINET) //等待到就将信号量减一
WaitForMultiObjects(DWORDnCount, CONST HANDLE *lpHandles, BOOL fWaitAll,DWORD dwMilliseconds)