阅读量:4
在Linux环境下,C++多线程实现同步主要有以下几种方法:
- 互斥锁(mutex):互斥锁是一种用于保护共享资源的同步原语。当一个线程访问共享资源时,它需要先锁定互斥锁,其他线程在互斥锁被解锁之前无法访问该资源。C++11提供了
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;
}
- 条件变量(condition_variable):条件变量允许线程在某个条件满足时等待或通知其他线程。C++11提供了
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::unique_lock 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;
}
- 原子操作(atomic):原子操作是一种不可中断的操作,可以确保在多线程环境下对共享变量的访问是安全的。C++11提供了
std::atomic模板类来实现原子操作。
示例:
#include
#include
#include
std::atomic<int> counter(0);
void increment_counter(int n) {
for (int i = 0; i < n; ++i) {
counter++;
}
}
int main() {
std::thread t1(increment_counter, 100000);
std::thread t2(increment_counter, 100000);
t1.join();
t2.join();
std::cout << "Counter: " << counter << '\n';
return 0;
}
- 屏障(barrier):屏障是一种同步原语,用于确保多个线程在继续执行之前都达到了某个点。C++11没有直接提供屏障,但可以使用
std::condition_variable和std::mutex实现。
示例:
#include
#include
#include
#include
#include
class Barrier {
public:
explicit Barrier(std::size_t count) : thread_count(count), count(count), generation(0) {}
void wait() {
std::unique_lock lock(mtx) ;
int gen = generation;
if (--count == 0) {
generation++;
count = thread_count;
cv.notify_all();
} else {
cv.wait(lock, [this, gen]{ return gen != generation; });
}
}
private:
std::mutex mtx;
std::condition_variable cv;
std::size_t thread_count;
std::size_t count;
int generation;
};
void print_id(int id, Barrier &barrier) {
std::cout << "Thread " << id << " before barrier\n";
barrier.wait();
std::cout << "Thread " << id << " after barrier\n";
}
int main() {
const int num_threads = 5;
Barrier barrier(num_threads);
std::vector threads;
for (int i = 0; i < num_threads; ++i) {
threads.push_back(std::thread(print_id, i, std::ref(barrier)));
}
for (auto &th : threads) {
th.join();
}
return 0;
}
这些方法可以根据具体需求进行选择和组合,以实现多线程之间的同步。
以上就是关于“Linux环境下C++多线程怎样实现同步”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm