Cpp Standard Library 简明教程

C++ Library - <thread>

Introduction

线程是一系列指令,可在多线程环境中与其他此类序列同时执行,同时共享同一地址空间。

Member types

Sr.No.

Member type & description

1

id 这是线程 ID。

2

Native handle type 这是本机句柄类型。

Member functions

Sr.No.

Member function & description

1

(constructor) 用于构造线程。

2

(destructor) 用于析构线程。

3

[role="bare"]../cpp_standard_library/cpp_thread_operator_equal.html是移动赋值线程。

4

get_id 用于获取线程 ID。

5

joinable 用于检查是否可加入。

6

join 用于加入线程。

7

detach 用于分离线程。

8

swap 用于交换线程。

9

native_handle 用于获取本机句柄。

10

hardware_concurrency [static] 用于检测硬件并行性。

Non-member overloads

Sr.No.

Non-member overload & description

1

swap (thread) 用于交换线程。

Example

在 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.