发布于2026-07-15 阅读(0)
扫一扫,手机访问
说到Ubuntu上用C++搞并发编程,其实路子不少。从C++11开始,标准库就自带了一套并发工具,用起来相当顺手。下面把这些常见方法过一遍,每个都附上代码示例,方便直接上手。

多线程 – 从C++11起,头文件就是创建线程的标配。写法很直白,比如:
#include
#include
void helloFunction() {
std::cout << "Hello from a thread!" << std::endl;
}
int main() {
std::thread t(helloFunction);
t.join(); // 等待线程完成
return 0;
}
互斥锁 – 多线程抢资源时,数据竞争是个大的麻烦。就是用来给共享资源上锁的,看个例子:
#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;
}
条件变量 – 线程间需要同步等待某个条件时,就派上用场了。比如下面这个“赛跑”的例子,所有线程都等一个信号才出发:
#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];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(printId, i);
std::cout << "10 threads ready to race...\n";
go();
for (auto &th : threads) th.join();
return 0;
}
原子操作 – 不想用锁,又想保证计数器这些简单操作线程安全?提供了无锁的原子类型,性能更好:
#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;
}
异步任务 – 想启动一个后台任务,等会儿再拿结果?和这套组合拳很合适:
#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 << "Waiting for the result...\n";
int value = result.get(); // 获取异步操作的结果
std::cout << "Got the result: " << value << std::endl;
return 0;
}
并行算法 – C++17开始,标准库里的算法(比如排序)可以带上并行执行策略,直接用头文件里的策略就行:
#include
#include
#include
#include
int main() {
std::vector v = {1, 2, 3, 4, 5};
std::sort(std::execution::par, v.begin(), v.end());
for (int i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
return 0;
}
编译时注意:如果你用了C++11或更高版本的特性,记得在编译命令里加上 -std=c++11(或 -std=c++17 等),并且如果用到线程,还要加 -pthread。比如:
g++ -std=c++11 -pthread your_program.cpp -o your_program
以上是C++并发编程的几种基础手段。实际项目中,往往需要组合使用这些技术才能应对复杂的并发场景。
下一篇:怎样设置有效的日志级别
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8