【C++多线程】std::timed_mutex带超时的互斥量

std::timed_mutex包含在头文件中。

【C++多线程】std::timed_mutex带超时的互斥量

用法和std::mutex类似。

【C++多线程】std::timed_mutex带超时的互斥量

  • try_lock_for():等待一段时间,如果拿到了锁,或者超时了未拿到锁,就继续执行(有选择执行)如下
1 std::chrono::milliseconds timeout(100);
2 if (my_mymutex.try_lock_for(timeout)){
3     //......拿到锁返回ture
4 }
5 else{
6     std::chrono::milliseconds sleeptime(100);
7     std::this_thread::sleep_for(sleeptime);
8 }
  • try_lock_until():参数是一个未来的时间点,在这个未来的时间没到的时间内,如果拿到了锁头,流程就走下来,如果时间到了没拿到锁,流程也可以走下来。
1 std::chrono::milliseconds timeout(100);
2 if (my_mymutex.try_lock_until(chrono::steady_clock::now() + timeout)){
3     //......拿到锁返回ture
4 }
5 else{
6     std::chrono::milliseconds sleeptime(100);
7     std::this_thread::sleep_for(sleeptime);
8 }

参考

https://blog.csdn.net/qq_38231713/article/details/106093490

原文链接: https://www.cnblogs.com/chen-cs/p/13254411.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200028

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:18
下一篇 2023年2月12日 下午8:19

相关推荐