在Linux下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的线程同步机制及其在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 print_block(int n, char c) {
mtx.lock(); // 加锁
if (n > 0) {
std::cout << c;
mtx.lock(); // 再次加锁
print_block(n - 1, c);
mtx.unlock(); // 解锁
}
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>
#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::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);
}
std::this_thread::sleep_for(std::chrono::seconds(1)); // 等待一段时间
go(); // 通知线程开始执行
for (auto& th : threads) {
th.join();
}
return 0;
}
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入共享资源。
#include <iostream>
#include <thread>
#include <shared_mutex>
std::shared_mutex rw_mtx; // 定义一个读写锁
int shared_data = 0;
void read_data() {
std::shared_lock<std::shared_mutex> lck(rw_mtx); // 读锁
std::cout << "Read data: " << shared_data << '\n';
}
void write_data(int value) {
std::unique_lock<std::shared_mutex> lck(rw_mtx); // 写锁
shared_data = value;
std::cout << "Write data: " << shared_data << '\n';
}
int main() {
std::thread readers[5];
std::thread writer(write_data, 42);
for (auto& th : readers) {
th = std::thread(read_data);
}
for (auto& th : readers) {
th.join();
}
writer.join();
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++中常用的线程同步机制。根据具体的需求选择合适的同步机制,可以有效地避免多线程编程中的竞态条件和死锁问题。