首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

Boost.Thread 線程同步與線程組實戰:mutex、condition_variable、thread_group

     編輯:C++ 入門

核心組件

  • boost::mutex:互斥鎖,保護共享數據
  • boost::condition_variable_any:條件變量,實現線程等待/通知
  • boost::unique_lock:RAII 風格鎖管理,自動加鎖/解鎖
  • boost::thread_group:線程集合管理,批量 join

案例一:生產者-消費者模式

一個線程生成隨機數,另一個線程打印,嚴格交替進行。

關鍵同步邏輯

boost::mutex mtx;
boost::condition_variable_any cond;
vector buffer;

void producer() {
    for (int i=0; i<3; i++) {
        boost::unique_lock lock(mtx);
        buffer.push_back(rand());
        cond.notify_all();  // 通知消費者
        cond.wait(lock);    // 等待消費者處理完
    }
}

void consumer() {
    size_t expected = 1;
    for (int i=0; i<3; i++) {
        boost::unique_lock lock(mtx);
        while (buffer.size() != expected) cond.wait(lock); // 條件檢查
        cout << buffer.back() << "---" << endl;
        ++expected;
        cond.notify_all(); // 通知生產者繼續
    }
}

關鍵點解析

  1. wait() 釋放鎖:調用 `wait` 時自動解鎖,被喚醒後重新加鎖
  2. while 而非 if:防止虛假喚醒,必須循環檢查條件
  3. notify_all vs notify_one:單生產單消費用 `notify_one` 更高效
  4. 鎖作用域:`unique_lock` 在離開作用域自動解鎖,異常安全

案例二:thread_group 批量管理

void task1() { cout << "task1\n"; }
void task2() { cout << "task2\n"; }

int main() {
    boost::thread_group grp;
    for (int i=0; i<3; i++) grp.create_thread(task1);
    grp.add_thread(new boost::thread(task2));
    
    cout << "Thread count: " << grp.size() << endl; // 4
    grp.join_all(); // 等待所有線程結束
}

thread_group 優勢

  • 統一管理動態創建的線程
  • `join_all()` 一次性等待所有線程
  • 自動處理線程對象生命週期(`add_thread` 接管所有權)
  • 異常時自動 join 已啟動線程,防資源洩漏

最佳實踐總結

  1. 共享數據必須用 `mutex` 保護
  2. 條件變量配合 `while(條件) wait()` 使用
  3. 優先使用 `unique_lock` 而非手動 `lock/unlock`
  4. 線程組管理多線程生命週期,簡化 `join` 調用
  5. 避免在持有鎖時調用耗時操作或阻塞調用

Boost.Thread 提供了現代 C++ 風格的線程同步原語,掌握「鎖 + 條件變量 + 線程組」組合拳,能高效解決多數並發編程問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved