阅读量:2
在Linux环境下使用C++进行多线程编程时,线程同步是一个重要的问题。以下是一些常用的线程同步方法:
1. 互斥锁(Mutex)
互斥锁是最基本的同步机制,用于保护共享资源,防止多个线程同时访问。
#include
#include
#include
std::mutex mtx;
int shared_data = 0;
void increment() {
mtx.lock();
++shared_data;
mtx.unlock();
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
2. 递归互斥锁(Recursive Mutex)
递归互斥锁允许同一个线程多次锁定同一个互斥锁,而不会导致死锁。
#include
#include
#include
std::recursive_mutex mtx;
int shared_data = 0;
void increment(int count) {
if (count <= 0) return;
mtx.lock();
++shared_data;
increment(count - 1);
mtx.unlock();
}
int main() {
std::thread t1(increment, 10);
std::thread t2(increment, 10);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
3. 条件变量(Condition Variable)
条件变量用于线程间的等待和通知机制。
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void worker() {
std::unique_lock lock(mtx) ;
cv.wait(lock, []{ return ready; });
std::cout << "Worker thread is processing data\n";
}
void trigger() {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::lock_guard lock(mtx) ;
ready = true;
cv.notify_one();
}
int main() {
std::thread t1(worker);
std::thread t2(trigger);
t1.join();
t2.join();
return 0;
}
4. 信号量(Semaphore)
信号量是一种计数器,用于控制对共享资源的访问。
#include
#include
#include
std::binary_semaphore sem(0);
int shared_data = 0;
void producer() {
std::this_thread::sleep_for(std::chrono::seconds(1));
++shared_data;
sem.release();
}
void consumer() {
sem.acquire();
std::cout << "Consumed data: " << shared_data << std::endl;
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}
5. 原子操作(Atomic Operations)
原子操作可以在不使用锁的情况下实现线程安全的操作。
#include
#include
#include
std::atomic<int> shared_data(0);
void increment() {
++shared_data;
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << "Shared data: " << shared_data << std::endl;
return 0;
}
总结
选择合适的同步方法取决于具体的应用场景和需求。互斥锁和条件变量是最常用的同步机制,而原子操作则适用于简单的计数操作。在实际编程中,应尽量避免复杂的同步逻辑,以减少潜在的死锁和竞态条件。
以上就是关于“Linux C++多线程同步方法”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm