Cpp Standard Library 简明教程

C++ Library - <thread>

Introduction

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

Thread is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address spac.

Member types

Sr.No.

Member type & description

1

idIt is a thread id.

2

Native handle type It is a native handle type.

Member functions

Sr.No.

Member function & description

1

(constructor)It is used to construct thread.

2

(destructor)It is used to destructor thread.

3

[role="bare"]../cpp_standard_library/cpp_thread_operator_equal.htmlIt is a move-assign thread.

4

get_idIt is used to get thread id.

5

joinableIt is used to check if joinable.

6

joinIt is used to join thread.

7

detachIt is used to detach thread.

8

swapIt is used to swap threads.

9

native_handleIt is used to get native handle.

10

hardware_concurrency [static]It is used to detect hardware concurrency.

Non-member overloads

Sr.No.

Non-member overload & description

1

swap (thread)It is used to swap threads.

Example

在 std::thread 以下示例中:

In below example for 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;
}

输出应类似于此 −

The output should be like this −

main, foo and bar now execute concurrently...
 bar is executing concurrently...
 foo is executing concurrently...
foo and bar completed.