首页 > 编程语言 >C++ timed_mutex

C++ timed_mutex

时间:2022-08-13 13:46:47浏览次数:117  
标签:std chrono lock C++ try mutex timed include

#include <iostream>
#include <thread>
#include <mutex>
   
std::timed_mutex mutex;

void mythread()
{
   std::chrono::milliseconds timeout(100); //100ms
   std::chrono::milliseconds sleep(100);

   while(true)
   {
      //if(mutex.try_lock_for(timeout))
      if(mutex.try_lock_until(std::chrono::steady_clock::now() + timeout))
      {
         std::cout << "try_lock_for" << std::endl;
         mutex.unlock();
      }
      else
      {
         std::this_thread::sleep_for(sleep);
      }
   }
}

int main()
{
   std::thread t(mythread);
   t.join();

   return 0;
}
$ g++ timed_mutex.cpp -std=c++11 -pthread
$ ./a.out
try_lock_for
try_lock_for

标签:std,chrono,lock,C++,try,mutex,timed,include
From: https://www.cnblogs.com/zhangxuechao/p/16582860.html

相关文章