#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