在高性能计算时代,掌握多线程编程是提升程序效率的必修课!本文将手把手教你如何用C++11标准库轻松创建和管理线程,告别单线程的“龟速”,让代码跑出多核CPU的性能!
一、多线程为何重要?
- 充分利用多核CPU:现代计算机普遍支持多核并行,多线程可让程序性能指数级提升。
- 提升用户体验:避免主线程阻塞,让界面操作与后台任务并行不悖。
- 解决计算密集型任务:如图像处理、大数据分析等场景。
二、创建线程的3种方式
1. 基础语法:用std::thread
启动线程
#include <thread>
#include <iostream>
void hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(hello); // 创建线程
t.join(); // 等待线程结束
return 0;
}
💡 关键点:
- 线程对象
std::thread t
创建后立即自动启动 join()
必须调用,否则程序会崩溃!
2. 传递参数:让线程更灵活
#include <string>
void print(const std::string& msg, int times) {
for(int i=0; i<times; ++i) std::cout << msg << std::endl;
}
int main() {
std::thread t(print, "Hello", 3); // 参数会被复制
t.join();
// 需要修改参数时,用std::ref传递引用
int count = 5;
std::thread t2(print, "ByRef", std::ref(count));
t2.join();
return 0;
}
3. Lambda表达式:匿名函数的优雅用法
int main() {
int x = 42;
std::thread t([x]