在C++中,多线程是通过让多个执行流同时运行来提升程序吞吐量和响应速度的手段。现代计算机多为多核CPU,如果只用单线程,其他核心往往处于空闲状态。合理地使用C++标准库中的多线程组件,可以把计算密集型或IO等待型任务分散到不同核心上,从而减少总耗时。

为什么单线程会成为性能瓶颈
当程序中存在大量循环计算、文件读写或网络请求时,单线程只能顺序执行。CPU的多个核心无法被利用,任务排队等待,导致延迟高、资源浪费。C++多线程正是为了解决这类问题而引入的并发方案。
C++中如何创建多线程
C++11起提供了<thread>头文件,可以用std::thread来启动新线程。下面示例展示两个线程并行做累加计算:
#include <iostream>
#include <thread>
#include <vector>
// 子线程执行的函数
void compute_sum(int start, int end, long long& result) {
long long temp = 0;
for (int i = start; i < end; ++i) {
temp += i;
}
result = temp;
}
int main() {
long long r1 = 0, r2 = 0;
// 创建两个线程分别处理不同区间
std::thread t1(compute_sum, 0, 5000000, std::ref(r1));
std::thread t2(compute_sum, 5000000, 10000000, std::ref(r2));
t1.join();
t2.join();
std::cout << "总和: " << (r1 + r2) << std::endl;
return 0;
}
多线程优化的关键注意点
- 任务划分要均衡,避免某个线程过早结束而另一些还在忙
- 共享数据需要用std::mutex等机制保护,否则会出现数据竞争
- 锁本身有开销,频繁加锁可能抵消并行带来的收益
- IO密集型任务可用异步线程避免阻塞主流程
用线程池减少创建开销
频繁创建和销毁线程成本较高,实际优化中常使用线程池。以下简单展示一个固定大小线程池的思路:
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>
class ThreadPool {
public:
ThreadPool(int n) {
for (int i = 0; i < n; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return !tasks.empty(); });
task = tasks.front();
tasks.pop();
}
task();
}
});
}
}
void add_task(std::function<void()> f) {
std::lock_guard<std::mutex> lock(mtx);
tasks.push(f);
cv.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex mtx;
std::condition_variable cv;
};
总结
多线程在C++性能优化里的作用主要体现在并行利用多核、隐藏IO延迟和拆分大任务。写好多线程程序需要权衡任务粒度、同步成本与资源占用,结合std::thread、互斥量和线程池等工具,才能让程序真正快起来。