Home > Back-end >  Linux c 11 STD: : unique_lock lock failure will return immediately, use try_lock_for function princi
Linux c 11 STD: : unique_lock lock failure will return immediately, use try_lock_for function princi

Time:09-21

First post code

#include
#include
#include
#include

STD: : timed_mutex tm_mtx;

Void thread_func ()
{
STD: : unique_lock & lt; STD: : timed_mutex & gt; Uqlk (tm_mtx, STD: : defer_lock);
If (uqlk. Try_lock_for (STD: : chrono: : seconds (5))) {
STD: : cout & lt; <"Get the lock success" & lt; STD: : this_thread: : sleep_for (STD: : chrono: : seconds (6));
STD: : cout & lt; <"Sleep over" & lt; }
The else {
STD: : cout & lt; <"Get the lock fail" & lt; }
}

Int main ()
{
STD: : thread td1 (thread_func);
Td1. Detach ();
STD: : thread td2 (thread_func);
Td2. Detach ();
getchar();
return 0;
}

Above, this code is run under Windows thread1 in acquiring the lock after dormancy 6 s; Thread2 attempt failed to get a lock within the 5 s, 5 s after printing the get the lock fail,
Linux, thread1 first get the lock, then thread2 attempt failed to get the lock, print directly get lok fail, does not trigger mechanism of 5 s, please explain, what reason be?
  • Related