在Linux環境下使用C++進行多線程編程時,線程同步是一個重要的問題。線程同步的目的是確保多個線程能夠安全地訪問共享資源,避免數據競爭和不一致性。以下是一些常用的線程同步機制:
互斥鎖是最基本的同步機制之一,用于保護共享資源,確保同一時間只有一個線程可以訪問該資源。
#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;
}
std::cout << '\n';
mtx.unlock(); // 解鎖
}
int main() {
std::thread th1(print_block, 50, '*');
std::thread th2(print_block, 50, '$');
th1.join();
th2.join();
return 0;
}
遞歸互斥鎖允許同一個線程多次鎖定同一個互斥鎖,而不會導致死鎖。
#include <iostream>
#include <thread>
#include <mutex>
std::recursive_mutex mtx;
void foo() {
mtx.lock();
std::cout << "foo\n";
mtx.lock(); // 再次鎖定
std::cout << "foo again\n";
mtx.unlock();
mtx.unlock();
}
int main() {
std::thread th(foo);
th.join();
return 0;
}
條件變量用于線程間的等待和通知機制,常與互斥鎖一起使用。
#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 << '\n';
}
void go() {
std::unique_lock<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);
}
std::this_thread::sleep_for(std::chrono::seconds(1));
go();
for (auto &th : threads) {
th.join();
}
return 0;
}
原子操作是不可分割的操作,可以確保在多線程環境下對變量的操作是線程安全的。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 100000; ++i) {
counter.fetch_add(1, std::memory_order_relaxed); // 原子加法
}
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Counter: " << counter.load() << '\n';
return 0;
}
屏障用于確保多個線程在某個點上同步,所有線程都到達屏障點后才能繼續執行。
#include <iostream>
#include <thread>
#include <vector>
#include <barrier>
std::barrier sync_point(3); // 創建一個屏障,等待3個線程
void do_work(int id) {
std::cout << "Thread " << id << " is working\n";
sync_point.arrive_and_wait(); // 等待其他線程
std::cout << "Thread " << id << " has passed the barrier\n";
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i) {
threads.emplace_back(do_work, i);
}
for (auto &th : threads) {
th.join();
}
return 0;
}
這些是C++多線程編程中常用的同步機制。根據具體的需求選擇合適的同步機制,可以有效地避免多線程編程中的常見問題。