日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

c++ 互斥量和条件变量

發布時間:2025/6/15 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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++ 互斥量和条件变量的全部內容,希望文章能夠幫你解決所遇到的問題。

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