阅读量:2
在Linux环境下使用C++多线程时,同步是一个重要的问题,以确保数据的一致性和线程安全。C++提供了多种同步机制,包括互斥锁(mutex)、条件变量(condition variable)、读写锁(reader-writer lock)等。以下是一些常见的同步方法:
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. 条件变量(Condition Variable)
条件变量用于线程间的通信,允许一个线程等待某个条件成立。
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_ready_message() {
std::unique_lock lck(mtx) ;
while (!ready) { // 如果ready为false,则等待
cv.wait(lck);
}
std::cout << "Ready!\n";
}
void set_ready() {
std::lock_guard lck(mtx) ;
ready = true;
cv.notify_one(); // 唤醒等待的线程
}
int main() {
std::thread th1(print_ready_message);
std::thread th2(set_ready);
th1.join();
th2.join();
return 0;
}
3. 读写锁(Reader-Writer Lock)
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入。
#include
#include
#include
#include
std::shared_mutex rw_mtx; // 读写锁
int data = 0;
void read_data() {
std::shared_lock lock(rw_mtx) ;
std::cout << "Read: " << data << '\n';
}
void write_data(int value) {
std::unique_lock lock(rw_mtx) ;
data = value;
std::cout << "Write: " << data << '\n';
}
int main() {
std::thread th1(read_data);
std::thread th2(write_data, 42);
std::thread th3(read_data);
th1.join();
th2.join();
th3.join();
return 0;
}
4. 原子操作(Atomic Operations)
原子操作是不可中断的操作,用于简单的同步需求。
#include
#include
#include
std::atomic<int> counter(0);
void increment() {
for (int i = 0; i < 1000; ++i) {
++counter;
}
}
int main() {
std::thread th1(increment);
std::thread th2(increment);
th1.join();
th2.join();
std::cout << "Counter: " << counter << '\n';
return 0;
}
总结
选择合适的同步机制取决于具体的应用场景和需求。互斥锁适用于简单的保护共享资源,条件变量适用于线程间的通信,读写锁适用于读多写少的场景,原子操作适用于简单的计数器等场景。在实际编程中,应根据具体情况选择合适的同步方法,以确保线程安全和数据一致性。
以上就是关于“linux c++多线程如何同步”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm