C++11 added a timed_mutex template class that allows you to try for a lock for a specified period of time. Here is an example:
#include <iostream>
#include <mutex>
#include <thread>
std::timed_mutex gTimedMutex;
int main()
{
if (gTimedMutex.try_lock_for(std::chrono::milliseconds(100)))
{
std::cout << "got_lock ";
}
else
{
std::cout << "try_lock_timeout ";
}
if (gTimedMutex.try_lock_for(std::chrono::milliseconds(100)))
{
std::cout << "got_lock ";
}
else
{
std::cout << "try_lock_timeout ";
}
gTimedMutex.unlock();
if (gTimedMutex.try_lock_for(std::chrono::milliseconds(100)))
{
std::cout << "got_lock ";
}
else
{
std::cout << "try_lock_timeout ";
}
std::cout << std::endl;
return 0;
}
// Output: got_lock try_lock_timeout got_lock
No comments:
Post a Comment