Home | History | Annotate | Download | only in thread.sharedtimedmutex.class
      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 // UNSUPPORTED: c++03, c++98, c++11
     12 
     13 // <shared_mutex>
     14 
     15 // class shared_timed_mutex;
     16 
     17 // template <class Rep, class Period>
     18 //     bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
     19 
     20 #include <shared_mutex>
     21 #include <thread>
     22 #include <cstdlib>
     23 #include <cassert>
     24 
     25 #include "test_macros.h"
     26 
     27 std::shared_timed_mutex m;
     28 
     29 typedef std::chrono::steady_clock Clock;
     30 typedef Clock::time_point time_point;
     31 typedef Clock::duration duration;
     32 typedef std::chrono::milliseconds ms;
     33 typedef std::chrono::nanoseconds ns;
     34 
     35 
     36 ms WaitTime = ms(250);
     37 
     38 // Thread sanitizer causes more overhead and will sometimes cause this test
     39 // to fail. To prevent this we give Thread sanitizer more time to complete the
     40 // test.
     41 #if !defined(TEST_HAS_SANITIZERS)
     42 ms Tolerance = ms(50);
     43 #else
     44 ms Tolerance = ms(50 * 5);
     45 #endif
     46 
     47 void f1()
     48 {
     49     time_point t0 = Clock::now();
     50     assert(m.try_lock_for(WaitTime + Tolerance) == true);
     51     time_point t1 = Clock::now();
     52     m.unlock();
     53     ns d = t1 - t0 - WaitTime;
     54     assert(d < Tolerance);  // within tolerance
     55 }
     56 
     57 void f2()
     58 {
     59     time_point t0 = Clock::now();
     60     assert(m.try_lock_for(WaitTime) == false);
     61     time_point t1 = Clock::now();
     62     ns d = t1 - t0 - WaitTime;
     63     assert(d < Tolerance);  // within tolerance
     64 }
     65 
     66 int main()
     67 {
     68     {
     69         m.lock();
     70         std::thread t(f1);
     71         std::this_thread::sleep_for(WaitTime);
     72         m.unlock();
     73         t.join();
     74     }
     75     {
     76         m.lock();
     77         std::thread t(f2);
     78         std::this_thread::sleep_for(WaitTime + Tolerance);
     79         m.unlock();
     80         t.join();
     81     }
     82 }
     83