boost库中mutex、condition_variable与mutex::scoped_lock联合使用实现线程之间的通信
生活随笔
收集整理的這篇文章主要介紹了
boost库中mutex、condition_variable与mutex::scoped_lock联合使用实现线程之间的通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近在公司負責一個線程池的模塊,里面用到了boost庫中的mutex、condition_variable與mutex::scoped_lock,在此總結下線程池在使用時的方式和要點,這里記錄了線程之間的通信方式,希望對學習線程之間(同一個進程)通信的同志們有所幫助。
線程之間(在同一個進程)的通信方式:信號量;mutex,條件變量和讀寫鎖。
class Condition {public:Condition() : count(0) { }virtual ~Condition() { }void Increase() {boost::mutex::scoped_lock lock(mutex);++ count;}void Decrease() {boost::mutex::scoped_lock lock(mutex);-- count;cond.notify_all(); //通知所有的線程}void Wait() {boost::mutex::scoped_lock lock(mutex);while (count > 0) {cond.wait(lock);}}private:boost::condition_variable cond; //條件變量boost::mutex mutex;int32_t count;};如果沒有boost庫,可以使用std::mutex, std::condition_variable代替,本人建議使用std標準庫中的。
總結
以上是生活随笔為你收集整理的boost库中mutex、condition_variable与mutex::scoped_lock联合使用实现线程之间的通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 51单片机超声波测距和报警+Proteu
- 下一篇: 基于GJB438C-2021的软件需求规