std::thread用法:创建、挂起、唤醒线程;线程ID转int

本文介绍了C++11中std::thread的使用,包括如何创建线程以及线程同步的方法。通过示例展示了std::thread::join()用于等待线程结束,std::thread::detach()使线程独立运行,以及如何获取线程ID并转换为字符串或整数。同时,讲解了线程睡眠的实现方式。
摘要由CSDN通过智能技术生成

1、线程常见用法:

// 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;
}

参考资料: std::thread

2、常用函数解释:
1、std::thread::join: 将该函数返回的时刻与该对象表示的线程所有操作执行完成的时间同步;同时阻止调用此函数的线程的执行,直到该线程执行完成。

2、std::thread::detach: 将对象表示的线程与调用线程分离,允许它们彼此独立执行
参考资料:http://www.cplusplus.com/reference/thread/thread/detach/

3、std::thread::get_id: 获取线程ID,返回值类型为thread::id,转换为string/int类型方式:

  • 转成string:
 #include <sstream>   
 auto myid = this_thread::get_id();   
 stringstream ss;   
 ss << myid;   
 string mystring = ss.str();   
  • 转成int:
 int x = stoi(mystring);  

注:在字符串mystring过长时,stoi函数会抛出异常导致程序挂掉,因此需要做容错处理,或者线程ID只按字符串输出
参考资料:
1、Linux下获取线程ID
2、C++11中stoi函数的异常处理

4、线程睡眠一定时长:

 std::this_thread::sleep_for(std::chrono::seconds(1));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值