C++在Linux上如何实现并发控制
导读:在Linux上使用C++实现并发控制,可以采用多种方法,包括线程、互斥锁、条件变量、信号量、读写锁等。以下是一些基本的实现方式: 1. 使用C++11标准库中的线程支持 C++11引入了线程库,提供了std::thread类来创建和管理线程...
在Linux上使用C++实现并发控制,可以采用多种方法,包括线程、互斥锁、条件变量、信号量、读写锁等。以下是一些基本的实现方式:
1. 使用C++11标准库中的线程支持
C++11引入了线程库,提供了std::thread类来创建和管理线程。
#include <
iostream>
#include <
thread>
void helloFunction() {
std::cout <
<
"Hello from a thread!" <
<
std::endl;
}
int main() {
std::thread t(helloFunction);
t.join();
// 等待线程完成
return 0;
}
2. 使用互斥锁(mutex)
互斥锁用于保护共享资源,确保同一时间只有一个线程可以访问。
#include <
iostream>
#include <
thread>
#include <
mutex>
std::mutex mtx;
// 创建一个互斥锁
void printMessage(const std::string&
msg) {
mtx.lock();
// 加锁
std::cout <
<
msg <
<
std::endl;
mtx.unlock();
// 解锁
}
int main() {
std::thread t1(printMessage, "Hello from thread 1");
std::thread t2(printMessage, "Hello from thread 2");
t1.join();
t2.join();
return 0;
}
3. 使用条件变量(condition_variable)
条件变量用于线程间的同步,允许一个或多个线程等待某个条件的发生。
#include <
iostream>
#include <
thread>
#include <
mutex>
#include <
condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(int id) {
std::unique_lock<
std::mutex>
lck(mtx);
cv.wait(lck, []{
return ready;
}
);
// 等待条件变量
std::cout <
<
"Thread " <
<
id <
<
std::endl;
}
void go() {
std::lock_guard<
std::mutex>
lck(mtx);
ready = true;
cv.notify_all();
// 通知所有等待的线程
}
int main() {
std::thread threads[10];
for (int i = 0;
i <
10;
++i)
threads[i] = std::thread(printId, i);
std::cout <
<
"10 threads ready to race..." <
<
std::endl;
go();
// 改变条件变量
for (auto&
th : threads)
th.join();
return 0;
}
4. 使用信号量(semaphore)
信号量是一种更底层的同步机制,可以用来控制对共享资源的访问。
#include <
iostream>
#include <
thread>
#include <
semaphore>
std::binary_semaphore sem(1);
// 创建一个二进制信号量
void critical_section() {
sem.acquire();
// 获取信号量
// 访问共享资源
std::cout <
<
"In critical section" <
<
std::endl;
sem.release();
// 释放信号量
}
int main() {
std::thread t1(critical_section);
std::thread t2(critical_section);
t1.join();
t2.join();
return 0;
}
5. 使用读写锁(shared_mutex)
读写锁允许多个线程同时读取共享资源,但只允许一个线程写入。
#include <
iostream>
#include <
thread>
#include <
shared_mutex>
std::shared_mutex rw_mtx;
int shared_data = 0;
void read_data() {
std::shared_lock<
std::shared_mutex>
lock(rw_mtx);
// 共享锁
std::cout <
<
"Read data: " <
<
shared_data <
<
std::endl;
}
void write_data(int new_value) {
std::unique_lock<
std::shared_mutex>
lock(rw_mtx);
// 排他锁
shared_data = new_value;
std::cout <
<
"Write data: " <
<
shared_data <
<
std::endl;
}
int main() {
std::thread t1(read_data);
std::thread t2(write_data, 42);
t1.join();
t2.join();
return 0;
}
在使用这些并发控制机制时,需要注意避免死锁和其他同步问题。合理设计程序的结构和使用适当的同步原语是确保线程安全的关键。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++在Linux上如何实现并发控制
本文地址: https://pptw.com/jishu/787358.html
