当前位置:网站首页>线程的支持

线程的支持

2022-06-24 06:44:00 雾散睛明

线程的支持
c标准库:
c标准库没有线程的支持,需使用平台原生的函数:
windows:CreateThread
unix:pthread_create 其实线程是用进程模拟的。
c++标准库

operator= 只支持右值做参数,使用的move 原来的线程对象变为不可 joinable
get_id 获取线程id
joinable 检测线程是否可以等待,空的thread 对象是不可等待的。
join 等待线程执行完成。
detach 分离线程对象和线程,此时thread对象不代表线程,线程依旧继续执行。
swap 交换
native_handle 获取原生平台的线程句柄。

this_thread:
get_id 获取当前线程的id
yield 放弃当前线程的时间片 相当于sleep(0)
sleep_until:休眠
sleep_for:休眠

从上面发现thread从创建开始就开始执行了,没有start、stop、pause、resume等行为。
示例:

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

boost库:
详见:
<boost/thread/thread.hpp>

原网站

版权声明
本文为[雾散睛明]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_25160759/article/details/116178791