Linux環境下c++多線程編程,線程同步至關重要。本文將介紹幾種常用的同步方法:
一、互斥鎖 (Mutex)
互斥鎖是基礎的同步機制,用于保護共享資源,防止數據競爭。
#include <iostream> #include <thread> #include <mutex> std::mutex mtx; // 全局互斥鎖 void print_block(int n, char c) { mtx.lock(); // 加鎖 for (int i = 0; i < n; ++i) { std::cout << c; } mtx.unlock(); // 解鎖 } int main() { std::thread th1(print_block, 50, '*'); std::thread th2(print_block, 50, '$'); th1.join(); th2.join(); return 0; }
二、條件變量 (Condition Variable)
立即學習“C++免費學習筆記(深入)”;
條件變量實現線程間的等待和通知。
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex mtx; std::condition_variable cv; bool ready = false; void print_id(int id) { std::unique_lock<std::mutex> lck(mtx); cv.wait(lck, []{return ready;}); // 等待條件滿足 std::cout << "thread " << id << std::endl; } void go() { std::lock_guard<std::mutex> lck(mtx); ready = true; cv.notify_all(); // 通知所有等待線程 } int main() { std::thread threads[10]; for (int i = 0; i < 10; ++i) { threads[i] = std::thread(print_id, i); } go(); for (auto& th : threads) { th.join(); } return 0; }
三、信號量 (Semaphore)
信號量是更高級的同步機制,控制對共享資源的訪問次數。
#include <iostream> #include <thread> #include <semaphore> std::binary_semaphore sem(0); // 二進制信號量 void print_block(int n, char c) { sem.acquire(); // 等待信號量 for (int i = 0; i < n; ++i) { std::cout << c; } } void go() { std::this_thread::sleep_for(std::chrono::seconds(1)); // 模擬任務 sem.release(); // 釋放信號量 } int main() { std::thread th1(print_block, 50, '*'); std::thread th2(print_block, 50, '$'); std::thread t(go); th1.join(); th2.join(); t.join(); return 0; }
四、原子操作 (Atomic Operations)
原子操作無需鎖即可保證線程安全。
#include <iostream> #include <thread> #include <atomic> std::atomic<int> counter(0); void increment() { for (int i = 0; i < 100000; ++i) { ++counter; } } int main() { std::thread t1(increment); std::thread t2(increment); t1.join(); t2.join(); std::cout << counter << std::endl; return 0; }
五、屏障 (Barrier)
屏障確保多個線程在特定點同步。
#include <iostream> #include <thread> #include <barrier> std::barrier bar(2); // 創建一個屏障,等待兩個線程 void print_hello() { std::cout << "Hello "; bar.wait(); // 等待屏障 std::cout << "World!" << std::endl; } int main() { std::thread t1(print_hello); std::thread t2(print_hello); t1.join(); t2.join(); return 0; }
選擇合適的同步機制取決于具體應用場景。 以上示例代碼僅供參考,實際應用中可能需要更復雜的同步策略。