C++ 锁的用法

Windows锁:
Mutex(互斥对象):内核对象,可以在多个进程中的各个线程间进行同步,一般用于排他的访问资源
Event(事件对象):内核对象,可以在多个进程中的各个线程间进行同步,一般用于控制线程的先后顺序
Critical Section(临界区):非内核对象,只能用于进程内的各个线程间进行同步,无法设定超时值

CRITICAL_SECTION cs;
InitializeCriticalSection(&cs);
EnterCriticalSection(&cs);
LeaveCriticalSection(&cs);
DeleteCriticalSection(&cs);

HANDLE mutex;
mutex = CreateMutex(NULL, FALSE, NULL);
WaitForSingleObject(mutex, INFINITE);
ReleaseMutex(mutex);
CloseHandle(mutex);

HANDLE event;
event = CreateEvent(NULL, TRUE, FALSE, NULL);
WaitForSingleObject(event, INFINITE);
SetEvent(event);
ResetEvent(event);
CloseHandle(event);

Linux锁:
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
pthread_mutex_tylock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);

posted @ 2013-05-09 20:46  Leung文  阅读(1345)  评论(0编辑  收藏  举报