Home | History | Annotate | Download | only in thread.timedmutex.recursive
      1 //===----------------------------------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is dual licensed under the MIT and the University of Illinois Open
      6 // Source Licenses. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // UNSUPPORTED: libcpp-has-no-threads
     11 
     12 // <mutex>
     13 
     14 // class recursive_timed_mutex;
     15 
     16 // template <class Rep, class Period>
     17 //     bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
     18 
     19 #include <mutex>
     20 #include <thread>
     21 #include <cstdlib>
     22 #include <cassert>
     23 
     24 std::recursive_timed_mutex m;
     25 
     26 typedef std::chrono::steady_clock Clock;
     27 typedef Clock::time_point time_point;
     28 typedef Clock::duration duration;
     29 typedef std::chrono::milliseconds ms;
     30 typedef std::chrono::nanoseconds ns;
     31 
     32 void f1()
     33 {
     34     time_point t0 = Clock::now();
     35     assert(m.try_lock_for(ms(300)) == true);
     36     time_point t1 = Clock::now();
     37     assert(m.try_lock());
     38     m.unlock();
     39     m.unlock();
     40     ns d = t1 - t0 - ms(250);
     41     assert(d < ns(50000000));  // within 50ms
     42 }
     43 
     44 void f2()
     45 {
     46     time_point t0 = Clock::now();
     47     assert(m.try_lock_for(ms(250)) == false);
     48     time_point t1 = Clock::now();
     49     ns d = t1 - t0 - ms(250);
     50     assert(d < ns(50000000));  // within 50ms
     51 }
     52 
     53 int main()
     54 {
     55     {
     56         m.lock();
     57         std::thread t(f1);
     58         std::this_thread::sleep_for(ms(250));
     59         m.unlock();
     60         t.join();
     61     }
     62     {
     63         m.lock();
     64         std::thread t(f2);
     65         std::this_thread::sleep_for(ms(300));
     66         m.unlock();
     67         t.join();
     68     }
     69 }
     70