您的位置:首页 >CentOS C++并发编程如何实现
发布于2026-04-26 阅读(0)
扫一扫,手机访问
要在CentOS系统上构建高效、稳健的并发程序,现代C++标准库已经为我们提供了一套强大而灵活的工具集。下面,我们就来梳理几种最常用、也最核心的并发编程模型,并配上可直接运行的代码示例,帮你快速上手。

创建和管理线程是并发编程的基础。C++11引入的头文件让这一切变得异常简单。你只需要定义一个函数,然后把它交给一个std::thread对象即可。
#include
#include
void helloFunction() {
std::cout << “Hello from a thread!” << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待线程完成
return 0;
}
看,启动一个线程就是这么直观。当然,别忘了使用join()等待线程结束,或者detach()让其独立运行。
当多个线程需要读写同一块数据时,数据竞争(Data Race)就成了头号敌人。这时,(互斥锁)就该登场了。它的作用是为临界区加锁,确保同一时间只有一个线程能访问共享资源。
#include
#include
#include
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;
}
不过,直接使用lock()和unlock()需要格外小心,万一在锁中间发生异常或提前返回,可能导致锁无法释放。更推荐的做法是使用std::lock_guard或std::unique_lock这类RAII(资源获取即初始化)包装器,让锁的生命周期自动管理。
如果线程之间需要更复杂的等待-通知机制,比如生产者-消费者模型,那么(条件变量)就是你的不二之选。它允许一个或多个线程等待某个条件成立,而其他线程则在条件满足时发出通知。
#include
#include
#include
#include
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void printId(int id) {
std::unique_lock lck(mtx);
cv.wait(lck, []{return ready;}); // 等待条件变量
std::cout << “Thread ” << id << std::endl;
}
void go() {
std::lock_guard lck(mtx);
ready = true;
cv.notify_all(); // 通知所有等待的线程
}
int main() {
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(printId, i);
std::cout << “10 threads ready to race...” << std::endl;
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
这个例子模拟了“赛跑”场景:10个线程各就各位,等待一声令下(ready变为true)。cv.notify_all()就是那声发令枪。
对于简单的计数器、标志位等操作,使用重量级的互斥锁可能有些“杀鸡用牛刀”。(原子操作)库提供了无需显式加锁就能保证操作原子性的类型,性能更高。
#include
#include
#include
std::atomic counter(0);
void incrementCounter() {
for (int i = 0; i < 1000; ++i) {
counter++; // 原子操作
}
}
int main() {
std::thread t1(incrementCounter);
std::thread t2(incrementCounter);
t1.join();
t2.join();
std::cout << “Counter: ” << counter << std::endl;
return 0;
}
无论运行多少次,这里的counter最终结果都将是确定的2000。原子操作是构建无锁数据结构和高性能并发组件的基石。
有时候,你只是想丢一个任务到后台去执行,然后在未来的某个时刻获取结果。和完美契合这种需求。它们帮你管理异步任务的启动和结果回收。
#include
#include
int asyncFunction() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
}
int main() {
std::future result = std::async(std::launch::async, asyncFunction);
// 可以在这里做其他事情
std::cout << “Result: ” << result.get() << std::endl; // 获取异步任务的结果
return 0;
}
通过std::async,你可以轻松实现任务的异步执行,主线程则继续处理其他工作,最后通过future.get()拿到计算结果。这为程序的响应性和资源利用提供了极大便利。
在CentOS上使用g++编译上述代码时,有两点至关重要:
g++ -std=c++11 -pthread your_program.cpp -o your_program
首先,-std=c++11(或更高标准如c++14、c++17)是必须的,因为并发库主要从C++11开始完善。其次,-pthread选项用于启用POSIX线程支持,这是链接线程库所必需的。
以上就是CentOS上C++并发编程的核心工具箱。实际开发中,这些技术往往需要根据具体场景组合使用。理解它们各自的适用边界,是构建出既高效又可靠的并发程序的关键。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9