std :: thread

头文件<thread>中包含两个类,thread和this_thread

在讲thread之前,首先要了解线程的一个状态:joinable

一个正规初始化后的线程是一个可执行线程,这种线程joinable为true,并且有一个独一无二的线程id。

相反,一个默认构造函数构造出的thread(thread(),没有参数,未初始化),joinable为false,且线程id通常和其他所有的non-joinable线程一样。


一个joinable线程被move from,或者调用join,detach后,变成non-joinable


1、成员类型

id  
native_handle_type  


2、成员函数

constructor
default (1)
thread() noexcept;
initialization (2)
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3)
thread (const thread&) = delete;
move (4)
thread (thread&& x) noexcept;

destructor 如果该线程是joinable,则调用terminate()
operator=
move (1)
thread& operator= (thread&& rhs) noexcept;
copy [deleted] (2)
thread& operator= (const thread&) = delete;

get_id Returns the thread id.
joinable check if joinable
join Join thread
detach Detach thread
swap  
native_handle Get native handle
hardware_concurrency [static] Detect hardware concurrency

3、非成员函数(重载)

swap


4、代码示例

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread
 
void foo() 
{
  // do stuff...
}

void bar(int x)
{
  // do stuff...
}

int main() 
{
  std::thread first (foo);     // spawn new thread that calls foo()
  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:
  first.join();                // pauses until first finishes
  second.join();               // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;
}

输出结果

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


你可能感兴趣的:(thread,多线程,C++,STL,C++11)