#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
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/280301.html