Linux下C++多线程如何实现同步
在Linux下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的同步机制:
1. 互斥锁(Mutex)
互斥锁是最基本的同步机制,用于保护共享资源,防止多个线程同时访问。
#include
#include
#include
std::mutex mtx; // 全局互斥锁
void print_block(int n, char c) {
mtx.lock(); // 加锁
for (int i = 0; i < n class="hljs-string">'\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, int count = 0) {
if (count >= 2) return; // 防止无限递归
mtx.lock(); // 加锁
std::cout << "Thread " << std class="hljs-built_in">get_id() << " is printing\n";
print_block(n, c, count + 1); // 递归调用
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 class="hljs-string">'\n';
}
void go() {
std::unique_lock 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. 原子操作(Atomic Operations)
原子操作可以在不使用锁的情况下实现线程安全的操作。
#include
#include
#include
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 class="hljs-built_in">load() << '\n'; // 输出计数器的值
return 0;
}
5. 屏障(Barrier)
屏障用于多个线程之间的同步,确保所有线程都到达某个点后再继续执行。
#include
#include
#include
#include
std::barrier sync_point(3); // 创建一个屏障,等待3个线程
void do_work(int id) {
std::cout << "Thread " << id class="hljs-string">" is working\n";
sync_point.arrive_and_wait(); // 等待其他线程
std::cout << "Thread " << id class="hljs-string">" has finished\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;
}
这些是Linux下C++多线程编程中常用的同步机制。根据具体的需求选择合适的同步机制,可以有效地保证线程安全。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权请联系我们,一经查实立即删除!