- 操作系统:ubuntu22.04
- IDE:Visual Studio Code
- 编程语言:C++11
算法描述
std::thread 是 C++11 标准库中用于创建和管理线程的核心类,定义在 头文件中。它使得多线程编程变得简单、类型安全且跨平台。
一、std::thread 简介
std::thread 是一个类,代表一个执行线程。你可以用它来启动一个函数(普通函数、lambda、函数对象、成员函数等)在新的线程中运行。
🔧 所需头文件:
#include <thread>
📦 常用成员函数:
| 函数 | 说明 |
|---|---|
| join() | 等待线程执行完毕(阻塞主线程) |
| detach() | 分离线程,让其在后台独立运行 |
| get_id() | 获取线程的唯一 ID |
| joinable() | 判断线程是否可以 join 或 detach |
| swap() | 交换两个 thread 对象 |
| native_handle() | 获取底层平台的原生线程句柄(如 pthread_t) |
二、创建线程的多种方式(附示例)
- 使用普通函数
#include <iostream>
#include <thread>
#include <chrono>
void hello()
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::thread t(hello); // 启动线程执行 hello 函数
std::cout << "Main thread ID: " << std::this_thread::get_id() << std::endl;
t.join(); // 等待线程结束
std::cout << "Thread joined." << std::endl;
return 0;
}
输出示例:
Main thread ID: 1
Hello from thread 2
Thread joined.
- 使用带参数的函数
void print_message(const std::string& msg, int n)
{
for (int i = 0; i < n; ++i)
{
std::cout << msg << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
int main()
{
std::thread t(print_message, "Hello from thread!", 3);
std
2万+



被折叠的 条评论
为什么被折叠?



