C++ Reference 之 Thread Class

C++ provides Thread (a class used to represent threads that are executed separately) thread class.

In a multithreaded environment, an executing thread is an instruction sequence that can be executed concurrently with the instruction sequence of other threads, and they share an address space.
An initialized thread object represents a valid thread of execution; such a thread is joinable and has a unique thread id.

A thread object constructed by default (not initialized) is non-joinable, and its thread id is shared with all non-joinable threads.
A joinable thread becomes non-joinable after being moved or after calling join or detach.

Member type:

id Thread id(public member type)
native_handle_type Native handle type(public member type)

Member function

Constructor
Destructor
operator= Move-assign thread(public)
get_id Get thread id(public)
joinable Check if thread is joinable(public)
join Join thread(public)
detach detach thread(public)
swap swap thread(public)
native_handle get native handle(public)
hardware_concurrency[static] Check hardware concurrency (public static)

Non-member overloaded function

swap(thread) 交换 threads (function)

Example

// thread example
#include <iostream>
#include <thread>

void foo() {
  std::cout << "foo" << std::endl;
}

void bar(int x) {
  std::cout << "bar int x" << std::endl;
}

int main() {
  // 创建一个调用 foo 接口的线程。
  std::thread first(foo);
  // 创建一个调用 bar 接口 参数为 int 的线程。
  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;
}

Guess you like

Origin blog.csdn.net/VOlsenBerg/article/details/103542484