阅读量:2
在Linux环境下,C++多线程同步主要有以下几种方法:
- 互斥锁(mutex):互斥锁是一种用于保护共享资源的同步原语。当一个线程访问共享资源时,它需要先锁定互斥锁,其他线程必须等待该线程解锁后才能访问共享资源。C++标准库提供了
std::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;
}
- 递归互斥锁(recursive mutex):递归互斥锁允许同一个线程多次锁定同一个互斥锁,而不会导致死锁。C++标准库提供了
std::recursive_mutex类来实现递归互斥锁。
#include
#include
#include
std::recursive_mutex mtx;
void print_block(int n, char c, int depth = 0) {
if (depth > 0) {
mtx.lock();
}
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
if (depth > 0) {
mtx.unlock();
}
}
int main() {
std::thread th1(print_block, 50, '*', 1);
std::thread th2(print_block, 50, '$', 2);
th1.join();
th2.join();
return 0;
}
- 条件变量(condition variable):条件变量允许线程在某个条件满足时等待,并在条件改变时被唤醒。C++标准库提供了
std::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;
}
- 读写锁(shared mutex):读写锁允许多个线程同时读取共享资源,但在写入共享资源时只允许一个线程访问。C++标准库提供了
std::shared_mutex类来实现读写锁。
#include
#include
#include
std::shared_mutex rw_mtx;
void read_block(int n, char c) {
std::shared_lock lck(rw_mtx) ;
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
void write_block(int n, char c) {
std::unique_lock lck(rw_mtx) ;
for (int i = 0; i < n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main() {
std::thread th1(read_block, 50, '*');
std::thread th2(write_block, 50, '$');
th1.join();
th2.join();
return 0;
}
这些同步方法可以帮助你在Linux环境下使用C++多线程编程时保护共享资源,避免数据竞争和其他并发问题。
以上就是关于“Linux环境下C++多线程同步方法是什么”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm