C++多线程编程通过std::thread实现,支持函数、Lambda创建线程,可传值或引用参数,需调用join()或detach()管理线程生命周期,并可使用hardware_concurrency()获取硬件并发数。

C++ 实现多线程编程主要通过标准库中的 std::thread 来完成。从 C++11 开始,C++ 标准提供了对多线程的原生支持,使得开发者无需依赖第三方库(如 pthread)也能轻松编写跨平台的多线程程序。
使用 std::thread 可以通过函数、函数对象、Lambda 表达式等方式创建线程。
基本语法:
#include <thread></thread>
#include <iostream>
#include <thread>
void say_hello() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
std::thread t(say_hello); // 启动新线程执行 say_hello
t.join(); // 等待线程结束
return 0;
}
#include <iostream>
#include <thread>
int main() {
std::thread t([](){
std::cout << "Lambda in thread" << std::endl;
});
t.join();
return 0;
}
向线程函数传递参数时,需在构造 thread 对象时一并传入。注意:默认是值传递,若要引用传递,必须使用 std::ref。
立即学习“C++免费学习笔记(深入)”;
示例:传参与引用传递#include <iostream>
#include <thread>
void print_num(int n, std::string& msg) {
n += 10;
msg += " (modified)";
std::cout << "n = " << n << ", msg = " << msg << std::endl;
}
int main() {
int val = 5;
std::string str = "Hello";
std::thread t(print_num, val, std::ref(str)); // 引用传递 str
t.join();
std::cout << "After thread: val = " << val << ", str = " << str << std::endl;
return 0;
}
输出中可以看到,val 的修改在线程内无效(值传递),而 str 被修改了(引用传递)。
每个 thread 对象有两种运行模式:
必须在 thread 对象销毁前调用其中之一,否则程序会终止(调用 std::terminate)。
示例:分离线程#include <iostream>
#include <thread>
#include <chrono>
void background_task() {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Background task done." << std::endl;
}
int main() {
std::thread t(background_task);
t.detach(); // 分离线程
std::cout << "Main thread continues..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3)); // 确保主线程不立即退出
return 0;
}
可以使用 std::thread::hardware_concurrency() 查询系统建议的最大并发线程数。
unsigned int max_threads = std::thread::hardware_concurrency(); std::cout << "Supports " << max_threads << " concurrent threads.\n";
这个值只是一个提示,可能返回 0(表示无法确定)。
基本上就这些。掌握 std::thread 的创建、参数传递、生命周期管理,就能应对大多数基础多线程场景。实际开发中常配合 mutex、条件变量等同步机制使用,避免数据竞争。以上就是c++++如何实现多线程编程_c++ std::thread使用方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号