C++ std::this_thread知识整理

std::this_thread::get_id()
std::this_thread::yield()
std::this_thread::sleep_for ()
std::this_thread::sleep_until ()

文章目录
前言
一、this_thread 是什么?
二、使用步骤
1.引入库
总结

前言
C++11新标准引入了四个支持多线程的文件,<atomic>、<thread>、<mutex>、<condition_variable>、<future>。

<thread>头文件主要声明了 std::thread 类,另外 std::this_thread 命名空间也在该头文件中。

 

提示:以下是本篇文章正文内容,下面案例可供参考

一、this_thread 是什么?
命名空间std::this_thread提供了一组关于当前线程的函数

二、使用步骤
1.引入库
<thread>

总结
使用this::this_thread::get_id()获取线程id:

函数原型:std::thread::id get_id() noexcept;

cout << this_thread::get_id() << endl;

thread t([] {cout << this_thread::get_id() << endl; });

t.detach();

system("pause");

 

使用std::this_thread::yield()放弃当前线程占用时间片使CPU重新调度以便其它线程执行:

函数原型:void yield() noexcept;

bool g_ready;

void waitReady() { while (!g_ready) { this_thread::yield(); } cout << "ok" << endl; }

thread t(waitReady);

t.detach();

 

使用std::this_thread::sleeo_for()阻塞当前线程一段时间:

函数原型:template< class Rep, class Period >
void sleep_for( const std::chrono::duration<Rep, Period>& sleep_duration );

this_thread::sleep_for(chrono::nanoseconds(1000));//阻塞当前线程1000纳秒

this_thread::sleep_for(chrono::microseconds(1000));//阻塞当前线程1000微妙

this_thread::sleep_for(chrono::milliseconds(1000));//阻塞当前线程1000毫秒

this_thread::sleep_for(chrono::seconds(20)+ chrono::minutes(1));//阻塞当前线程1分钟20秒

this_thread::sleep_for(chrono::hours(1));//阻塞当前线程1小时

 

使用std::this_thread::sleeo_until()阻塞当前线程直到某个时间点:

函数原型:template< class Clock, class Duration >
void sleep_until( const std::chrono::time_point<Clock,Duration>& sleep_time );

chrono::system_clock::time_point until = chrono::system_clock::now();

until += chrono::seconds(5);

this_thread::sleep_until(until);//阻塞到5秒之后
————————————————
版权声明:本文为CSDN博主「那条暗黑的狼」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_38515565/article/details/109473172

posted @   冰山奇迹  阅读(339)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示