使用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 可以捕获局部变量,适合在局部作用域中启动线程。
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)
多个线程访问共享资源时,需要加锁防止数据竞争。
#include 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 lock(mtx); ++shared_data; }}
5. 使用 std::async 和 std::future 获取返回值
适用于需要异步执行并获取结果的场景。
#include int 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)互斥锁和条件变量(std::mutex, std::condition_variable)停止标志
基本上就这些常见用法。C++多线程编程的关键是掌握 std::thread、std::mutex、std::lock_guard、std::async 和 std::future。合理使用这些工具,可以写出高效且安全的并发程序。
以上就是c++++怎么实现多线程_c++多线程实现方法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1476990.html
微信扫一扫
支付宝扫一扫