std::timed_mutex包含在<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

 

相关文章:

  • 2022-02-11
  • 2021-07-29
  • 2021-09-27
  • 2022-12-23
  • 2021-07-20
  • 2021-06-26
  • 2021-06-05
  • 2022-12-23
猜你喜欢
  • 2021-06-29
  • 2021-06-25
  • 2022-01-22
  • 2021-08-25
  • 2022-02-03
  • 2022-12-23
  • 2022-01-24
相关资源
相似解决方案