阅读量:1
在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; ++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 rmtx;
void func(int n) {
if (n <= 0) return;
rmtx.lock();
std::cout << "Thread " << std::this_thread::get_id() << " is in func\n";
func(n - 1);
rmtx.unlock();
}
int main() {
std::thread th1(func, 4);
std::thread th2(func, 3);
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. 原子操作(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.load() << '\n'; // 输出 200000
return 0;
}
5. 屏障(Barrier)
屏障用于多个线程之间的同步,确保所有线程都到达某个点后再继续执行。
#include
#include
#include
#include
std::barrier sync_point(3); // 创建一个屏障,等待3个线程
void do_work(int id) {
std::cout << "Thread " << id << " is doing work\n";
sync_point.arrive_and_wait(); // 等待其他线程
std::cout << "Thread " << id << " has finished work\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++ Linux下多线程同步方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm