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

在C++中实现多线程,最常用的方式是使用标准库中的 std::thread。从 C++11 开始,C++ 提供了对多线程的原生支持,无需依赖第三方库或平台特定的API(如 Windows 的 CreateThread 或 POSIX 的 pthread)。以下是几种常见的C++多线程实现方法。
最基本的多线程实现方式是创建一个 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;
}
注意:必须调用 join() 或 detach(),否则程序在主线程结束时会调用 std::terminate()。
立即学习“C++免费学习笔记(深入)”;
可以向线程函数传递参数,但要注意默认是按值传递。如果需要引用,应使用 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;
}
Lambda 可以捕获局部变量,适合在局部作用域中启动线程。
int main() {
int id = 1;
std::thread t([id]() {
std::cout << "Lambda thread with id: " << id << std::endl;
});
t.join();
return 0;
}
多个线程访问共享资源时,需要加锁防止数据竞争。
#include <mutex>
std::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<std::mutex> lock(mtx);
++shared_data;
}
}
适用于需要异步执行并获取结果的场景。
#include <future>
int compute() {
return 42;
}
int main() {
std::future<int> result = std::async(compute);
std::cout << "Result: " << result.get() << std::endl; // 阻塞等待结果
return 0;
}
实际项目中常使用线程池避免频繁创建销毁线程。虽然标准库没有直接提供线程池,但可以用队列 + 多个线程 + 条件变量实现。
核心组件包括:
基本上就这些常见用法。C++多线程编程的关键是掌握 std::thread、std::mutex、std::lock_guard、std::async 和 std::future。合理使用这些工具,可以写出高效且安全的并发程序。
以上就是c++++怎么实现多线程_c++多线程实现方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号