当前位置: 首页 > news >正文

C++11中std::thread的使用

C++11 引入了 std::thread,它是用于创建和管理线程的标准库类。以下是详细的讲解,包括如何使用 std::thread 进行线程创建、管理和参数传递等操作。

1. 包含必要的头文件

在使用 std::thread 前,需要包含 <thread> 头文件:

#include <thread>

2. 创建和启动线程

可以通过传递一个可调用对象(函数、lambda 表达式或函数对象)给 std::thread 的构造函数来创建和启动线程。

示例:使用函数
#include <iostream>
#include <thread>void printMessage(const std::string& message) {std::cout << message << std::endl;
}int main() {std::thread t(printMessage, "Hello from the thread!");t.join(); // 等待线程完成return 0;
}
示例:使用 lambda 表达式
#include <iostream>
#include <thread>int main() {std::thread t([]() {std::cout << "Hello from the lambda thread!" << std::endl;});t.join(); // 等待线程完成return 0;
}

3. 等待线程完成

使用 join 方法可以阻塞主线程,直到被 join 的线程执行完毕。

t.join();

4. 分离线程

使用 detach 方法可以将线程分离,分离后的线程在后台独立运行,直到执行完毕。

t.detach();

5. 传递参数给线程

可以通过构造函数传递参数给线程函数。

示例:传递多个参数
#include <iostream>
#include <thread>void printValues(int a, double b) {std::cout << "a = " << a << ", b = " << b << std::endl;
}int main() {std::thread t(printValues, 10, 3.14);t.join();return 0;
}

6. 使用 std::ref 传递引用参数

默认情况下,std::thread 会复制传递给它的参数。如果需要传递引用,可以使用 std::ref

示例:传递引用参数
#include <iostream>
#include <thread>
#include <functional> // std::refvoid printMessage(const std::string& message) {std::cout << message << std::endl;
}int main() {std::string message = "Hello from the reference thread!";std::thread t(printMessage, std::ref(message));t.join();return 0;
}

7. 检查线程是否可联结(joinable)

可以使用 joinable 方法检查线程是否可以 join。如果一个线程已经被 joindetach,那么它将不再是可联结的。

if (t.joinable()) {t.join();
}

8. 线程的异常处理

可以在线程函数中使用异常处理机制(如 try-catch 块)来捕获和处理异常。

示例:在线程中处理异常
#include <iostream>
#include <thread>void threadFunction() {try {throw std::runtime_error("An error occurred");} catch (const std::exception& e) {std::cerr << "Exception caught in thread: " << e.what() << std::endl;}
}int main() {std::thread t(threadFunction);t.join();return 0;
}

9. 线程的硬件并发性

可以使用 std::thread::hardware_concurrency 来获取系统支持的并发线程数。

unsigned int n = std::thread::hardware_concurrency();
std::cout << "Number of concurrent threads supported: " << n << std::endl;

10. 使用 std::asyncstd::future 管理异步任务

除了 std::thread,C++11 还引入了 std::asyncstd::future 来简化异步任务的管理。

示例:使用 std::async
#include <iostream>
#include <future>int compute() {return 42;
}int main() {std::future<int> result = std::async(compute);std::cout << "Result from async: " << result.get() << std::endl;return 0;
}

参考文献

  • C++ Reference
  • ISO C++ Foundation
  • Thread Management in C++11

通过以上步骤和示例,可以较全面地了解和使用 C++11 中的 std::thread 来进行多线程编程。

http://www.lryc.cn/news/385322.html

相关文章:

  • 酷瓜云课堂(内网版)v1.1.5 发布,局域网在线学习+考试系统
  • 大数据之Hadoop部署
  • Java异常处理中的“throw”与“throws”的区别
  • 英语智汇学习系统
  • ExtractAItoTEXT 提取Adobe illustrator AI文件中的文字到文本文件翻译并写回到Adobe illustrator AI文件
  • ms17-010 ms12-020 ms-08-067
  • 【海思Hi3403V100】多目拼接相机套板硬件规划方案
  • AI的赚钱风向,彻底变了!
  • 服务器重启后jenkins任务内容不见了,并且新建任务也不见了
  • 如何选择合适的WordPress主机?
  • 面试突击:Java 集合知识体系梳理
  • AI智能管理系统设计文档
  • 干涉阵型成图参数记录【robust】
  • React Native工程运行时下载gradle超时问题
  • 本地离线模型搭建指南-LLaMA-Factory训练框架及工具
  • 数智化金融采购系统特点
  • 使用 SwiftUI 为 macOS 创建类似于 App Store Connect 的选择器
  • Python26 Lambda表达式
  • 2024年数据、自动化与智能计算国际学术会议(ICDAIC 2024)
  • cuda 学习笔记4
  • ZSWatch 开源项目介绍
  • Ansible-综合练习-生产案例
  • lombok关于构造器的注解的坑【避坑】
  • 指针并不是用来存储数据的,而是用来存储数据在内存中地址(内存操作/函数指针/指针函数)
  • iso21434认证的意义
  • 分页处理封装+分页查询题目列表
  • 每天一个项目管理概念之WBS
  • linux安装mysql8并查看密码
  • [渗透测试] 任意文件读取漏洞
  • sudo: /etc/init.d/ssh: command not found