使用std::thread实现多线程是C++11起的标准方法,支持函数、lambda和函数对象作为线程目标,无需依赖平台API。

在C++中实现多线程,最常用的方式是使用标准库中的 std::thread。从 C++11 开始,C++ 提供了对多线程的原生支持,无需依赖第三方库或平台特定的API(如 Windows 的 CreateThread 或 POSIX 的 pthread)。以下是几种常见的C++多线程实现方法。
1. 使用 std::thread 创建线程
最基本的多线程实现方式是创建一个 std::thread 对象,并传入一个可调用的目标(函数、lambda表达式、函数对象等)。
示例代码:
#include#include void say_hello() { std::cout << "Hello from thread!" << std::endl; } int main() { std::thread t(say_hello); // 启动线程 t.join(); // 等待线程结束 return 0; }
注意:必须调用 join() 或 detach(),否则程序在主线程结束时会调用 std::terminate()。
立即学习“C++免费学习笔记(深入)”;
2. 传递参数给线程函数
可以向线程函数传递参数,但要注意默认是按值传递。如果需要引用,应使用 std::ref。
void print_number(int& n) {
n += 10;
std::cout << "Thread: n = " << n << std::endl;
}
int main() {
int num = 5;
std::thread t(print_number, std::ref(num)); // 使用 std::ref 传递引用
t.join();
std::cout << "Main: num = " + num << std::endl; // 输出 15
return 0;
}
3. 使用 Lambda 表达式创建线程
Lambda 可以捕获局部变量,适合在局部作用域中启动线程。
BJXShop网上购物系统是一个高效、稳定、安全的电子商店销售平台,经过近三年市场的考验,在中国网购系统中属领先水平;完善的订单管理、销售统计系统;网站模版可DIY、亦可导入导出;会员、商品种类和价格均实现无限等级;管理员权限可细分;整合了多种在线支付接口;强有力搜索引擎支持... 程序更新:此版本是伴江行官方商业版程序,已经终止销售,现于免费给大家使用。比其以前的免费版功能增加了:1,整合了论坛
int main() {
int id = 1;
std::thread t([id]() {
std::cout << "Lambda thread with id: " << id << std::endl;
});
t.join();
return 0;
}
4. 线程同步:互斥锁(std::mutex)
多个线程访问共享资源时,需要加锁防止数据竞争。
#includestd::mutex mtx; int shared_data = 0; void safe_increment() { for (int i = 0; i < 100000; ++i) { mtx.lock(); ++shared_data; mtx.unlock(); } } int main() { std::thread t1(safe_increment); std::thread t2(safe_increment); t1.join(); t2.join(); std::cout << "Final value: " << shared_data << std::endl; // 应为 200000 return 0; }
更推荐使用 std::lock_guard 实现RAII自动加锁解锁:
void safe_increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard lock(mtx);
++shared_data;
}
}
5. 使用 std::async 和 std::future 获取返回值
适用于需要异步执行并获取结果的场景。
#includeint compute() { return 42; } int main() { std::future result = std::async(compute); std::cout << "Result: " << result.get() << std::endl; // 阻塞等待结果 return 0; }
6. 线程池(高级用法)
实际项目中常使用线程池避免频繁创建销毁线程。虽然标准库没有直接提供线程池,但可以用队列 + 多个线程 + 条件变量实现。
核心组件包括:
- 任务队列(std::queue)
- 线程集合(std::vector<:thread>)
- 互斥锁和条件变量(std::mutex, std::condition_variable)
- 停止标志
基本上就这些常见用法。C++多线程编程的关键是掌握 std::thread、std::mutex、std::lock_guard、std::async 和 std::future。合理使用这些工具,可以写出高效且安全的并发程序。









