C++ 标准库 - <thread>
简介
线程是可以在多线程环境中与其他此类序列同时执行的指令序列,同时共享相同的地址空间。
成员类型
| 序号 | 成员类型 & 说明 |
|---|---|
| 1 | id
它是一个线程 ID。 |
| 2 | Native handle type
它是本机句柄类型。 |
成员函数
| 序号 | 成员函数 & 说明 |
|---|---|
| 1 | (constructor)
它用于构造线程。 |
| 2 | (destructor)
它用于析构线程。 |
| 3 | operator=
它是一个移动分配线程。 |
| 4 | get_id
它用于获取线程ID。 |
| 5 | joinable
它用于检查是否可连接。 |
| 6 | join
它用于连接线程。 |
| 7 | detach
它用于分离线程。 |
| 8 | swap
它用于交换线程。 |
| 9 | native_handle
它用于获取本机句柄。 |
| 10 | hardware_concurrency [static]
它用于检测硬件并发性。 |
非成员重载
| 序号 | 非成员重载 & 说明 |
|---|---|
| 1 | swap (thread)
它用于交换线程。 |
示例
在下面的 std::thread 示例中。
#include <iostream>
#include <thread>
void foo() {
std::cout << " foo is executing concurrently...\n";
}
void bar(int x) {
std::cout << " bar is executing concurrently...\n";
}
int main() {
std::thread first (foo);
std::thread second (bar,0);
std::cout << "main, foo and bar now execute concurrently...\n";
first.join();
second.join();
std::cout << "foo and bar completed.\n";
return 0;
}
输出应该是这样的 −
main, foo and bar now execute concurrently... bar is executing concurrently... foo is executing concurrently... foo and bar completed.

