C++11引入std::thread,通过#include <thread>使用,支持函数、lambda创建线程,参数传递需用std::ref包装引用,线程必须join或detach,可结合vector管理多线程。

在C++11中,std::thread被引入标准库,使得多线程编程变得更加简单和安全。通过#include <thread>即可使用,无需依赖平台特定的API(如pthread)。下面介绍如何用std::thread创建和管理线程。
使用std::thread构造函数启动一个新线程,传入一个可调用对象(函数、lambda、函数对象等)作为线程执行体。
#include <iostream>
#include <thread>
void say_hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(say_hello); // 启动线程
t.join(); // 等待线程结束
return 0;
}
std::thread t([](){
std::cout << "Lambda thread running." << std::endl;
});
t.join();
可以在创建线程时向线程函数传递参数,注意默认是按值传递。若需引用,必须使用std::ref包装。
void print_number(int& n) {
n *= 2;
std::cout << "Thread: " << n << std::endl;
}
int main() {
int num = 42;
std::thread t(print_number, std::ref(num)); // 必须用std::ref才能传引用
t.join();
std::cout << "Main: " << num << std::endl; // 输出84
return 0;
}
每个std::thread对象在销毁前必须明确处理其关联的执行线程,否则程序会终止(调用std::terminate)。
立即学习“C++免费学习笔记(深入)”;
std::thread对象关联。之后无法再join。
std::thread t([]{
for(int i = 0; i < 5; ++i)
std::cout << i << " ";
});
// t.detach(); // 分离线程,独立运行
t.join(); // 等待线程完成
建议优先使用join(),除非确实需要后台异步执行且不关心结果。
可以使用std::vector<std::thread>来管理多个线程。
#include <vector>
std::vector<std::thread> threads;
// 创建10个线程
for (int i = 0; i < 10; ++i) {
threads.emplace_back([i](){
std::cout << "Thread " << i << " running.\n";
});
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
基本上就这些。只要记得每个线程都要join或detach,传引用加std::ref,避免数据竞争,就能安全使用std::thread。不复杂但容易忽略细节。
以上就是C++如何使用std::thread创建和管理线程_C++ std::thread使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号