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_idReturns the thread id.
joinablecheck if joinable
joinJoin thread
detachDetach thread
swap 
native_handleGet 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值