阅读量:1
在Linux下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的线程同步机制及其在C++中的实现方法:
1. 互斥锁(Mutex)
互斥锁用于保护共享资源,确保同一时间只有一个线程可以访问该资源。
#include
#include
#include
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;
}
2. 递归互斥锁(Recursive Mutex)
递归互斥锁允许同一个线程多次锁定同一个互斥锁,而不会导致死锁。
#include
#include
#include
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;
}
3. 条件变量(Condition Variable)
条件变量用于线程间的等待和通知机制。
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock lck(mtx) ;
cv.wait(lck, []{return ready;}); // 等待条件变量
std::cout << "Thread " << id << '\n';
}
void go() {
std::lock_guard 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;
}
4. 读写锁(Reader-Writer Lock)
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入共享资源。
#include
#include
#include
std::shared_mutex rw_mtx; // 定义一个读写锁
int shared_data = 0;
void read_data() {
std::shared_lock lck(rw_mtx) ; // 读锁
std::cout << "Read data: " << shared_data << '\n';
}
void write_data(int value) {
std::unique_lock 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;
}
5. 屏障(Barrier)
屏障用于确保多个线程在某个点上同步,所有线程都到达屏障点后才能继续执行。
#include
#include
#include
#include
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 threads;
for (int i = 0; i < 3; ++i) {
threads.emplace_back(do_work, i);
}
for (auto& th : threads) {
th.join();
}
return 0;
}
这些是C++中常用的线程同步机制。根据具体的需求选择合适的同步机制,可以有效地避免多线程编程中的竞态条件和死锁问题。
以上就是关于“Linux下C++如何处理多线程同步”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm