C++11 标准库 线程库<thread>梳理
目录[*]
[*]this_thread命名空间
[*]1. get_id()
[*]2. sleep_for()
[*]3. sleep_until()
[*]4. yield()
[*]thread类
[*]构造函数:
[*]类方法
[*]1. get_id()
[*]2. join()
[*]3. detach()
[*]4. joinable()
[*]5. operator=
[*]6. hardware_concurrency(static)
[*]多线程的两种计算场景
this_thread命名空间
在C++11中不仅添加了线程类,还添加了一个关于线程的命名空间std::this_thread,在这个命名空间中提供了四个公共的成员函数,通过这些成员函数就可以对当前线程进行相关的操作了。
头文件
1. get_id()
函数原型
thread::id get_id() noexcept;
get_id可以获取主调线程的id,即在主线程中获取到的是主线程id,在子线程中获取到的是子线程id.
注:在VS中,线程id被封装了一层,是一个结构体.
https://img2023.cnblogs.com/blog/2921710/202407/2921710-20240713185147166-1958992942.png
2. sleep_for()
命名空间this_thread中提供了一个休眠函数sleep_for(),调用这个函数的线程会马上从运行态变成阻塞态并在这种状态下休眠一定的时长,因为阻塞态的线程已经让出了CPU资源,代码也不会被执行,所以线程休眠过程中对CPU来说没有任何负担。程序休眠完成之后,会从阻塞态重新变成就绪态,就绪态的线程需要再次争抢CPU时间片,抢到之后才会变成运行态,这时候程序才会继续向下运行。
这个函数是函数原型如下,参数需要指定一个休眠时长,是一个时间段:
template <class Rep, class Period>
void sleep_for (const chrono::duration<Rep,Period>& rel_time);示例:
#include#includeint main() { std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); std::this_thread::sleep_for(std::chrono::seconds()); std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::chrono::nanoseconds ret = end - start; std::cout
页:
[1]