日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

c++ 互斥量和条件变量

發布時間:2025/6/15 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c++ 互斥量和条件变量 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ? 線程同步時會遇到互斥量和條件變量配合使用的情況,下面看一下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; };

將互斥量和條件變量對應的API封裝起來,ScopedLock的構造自動加鎖,析構自動釋放鎖很便捷。

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; }

運行結果為:func1 Wait
? ? ? ? ? ? ? ? ? ? ? func2 Signal
? ? ? ? ? ? ? ? ? ? ? func2_count =1
? ? ? ? ? ? ? ? ? ? ? func1_count =2

? pthread_cond_wait(&_cond, _mutex)內部有釋放互斥鎖的操作,不然func2不可能獲取到互斥鎖。ScopedLock避免了C語言的手動釋放鎖的操作。

總結

以上是生活随笔為你收集整理的c++ 互斥量和条件变量的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。