c++ 互斥量和条件变量
生活随笔
收集整理的這篇文章主要介紹了
c++ 互斥量和条件变量
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ? ? 線程同步時(shí)會(huì)遇到互斥量和條件變量配合使用的情況,下面看一下C++版的。
test.h
#include <pthread.h> #include <iostream>class T_Mutex { public:T_Mutex() { pthread_mutex_init(&mutex_, NULL); }~T_Mutex() { pthread_mutex_destroy(&mutex_); }void Lock() { pthread_mutex_lock(&mutex_); }void Unlock() { pthread_mutex_unlock(&mutex_); }pthread_mutex_t *getMutex() { return &mutex_; }private:pthread_mutex_t mutex_; };class T_Condition { public:T_Condition(pthread_mutex_t *mutex) : _mutex(mutex) {pthread_cond_init(&_cond, NULL);}~T_Condition() {pthread_cond_destroy(&_cond);}int Wait() { pthread_cond_wait(&_cond, _mutex); }void Signal() { pthread_cond_signal(&_cond); }void Broadcast() { pthread_cond_broadcast(&_cond); }private:pthread_cond_t _cond;pthread_mutex_t *_mutex; };class T_MutexCond : public T_Mutex, public T_Condition { public:explicit T_MutexCond(void) : T_Mutex(), T_Condition(getMutex()) {} };class ScopedLock { public:explicit ScopedLock(pthread_mutex_t *mutex) : m_mutex(mutex) { //傳入mutexpthread_mutex_lock(m_mutex);}explicit ScopedLock(T_Mutex *mutex) : m_mutex(mutex->getMutex()) { //傳入T_Mutexpthread_mutex_lock(m_mutex);}~ScopedLock() {pthread_mutex_unlock(m_mutex); }private:ScopedLock();pthread_mutex_t *m_mutex; };將互斥量和條件變量對(duì)應(yīng)的API封裝起來(lái),ScopedLock的構(gòu)造自動(dòng)加鎖,析構(gòu)自動(dòng)釋放鎖很便捷。
test.cpp
#include <iostream> #include <pthread.h> #include <unistd.h> #include <stdio.h> #include "test.h"T_MutexCond m_cond; unsigned count = 0;void *func1(void *arg) {ScopedLock lock(&m_cond);while(count == 0){printf("func1 Wait\n");m_cond.Wait();}count = count + 1;printf("func1_count =%d\n",count); }void *func2(void *arg) {ScopedLock lock(&m_cond);if(count == 0){printf("func2 Signal\n");m_cond.Signal();}count = count + 1;printf("func2_count =%d\n",count); }int main(void) {pthread_t tid1, tid2;pthread_create(&tid1, NULL, func1, NULL);sleep(5);pthread_create(&tid2, NULL, func2, NULL);pthread_join(tid1, NULL);pthread_join(tid2, NULL);return 0; }運(yùn)行結(jié)果為:func1 Wait
? ? ? ? ? ? ? ? ? ? ? func2 Signal
? ? ? ? ? ? ? ? ? ? ? func2_count =1
? ? ? ? ? ? ? ? ? ? ? func1_count =2
? pthread_cond_wait(&_cond, _mutex)內(nèi)部有釋放互斥鎖的操作,不然func2不可能獲取到互斥鎖。ScopedLock避免了C語(yǔ)言的手動(dòng)釋放鎖的操作。
總結(jié)
以上是生活随笔為你收集整理的c++ 互斥量和条件变量的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c++ try...catch异常处理
- 下一篇: getrlimit读取进程能打开的最大文