Home | History | Annotate | Download | only in thread.lock.shared.cons
      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 // <shared_mutex>
     11 
     12 // class timed_mutex;
     13 
     14 // template <class Rep, class Period>
     15 //   shared_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time);
     16 
     17 #include <shared_mutex>
     18 #include <thread>
     19 #include <vector>
     20 #include <cstdlib>
     21 #include <cassert>
     22 
     23 #if _LIBCPP_STD_VER > 11
     24 
     25 std::shared_timed_mutex m;
     26 
     27 typedef std::chrono::steady_clock Clock;
     28 typedef Clock::time_point time_point;
     29 typedef Clock::duration duration;
     30 typedef std::chrono::milliseconds ms;
     31 typedef std::chrono::nanoseconds ns;
     32 
     33 void f1()
     34 {
     35     time_point t0 = Clock::now();
     36     std::shared_lock<std::shared_timed_mutex> lk(m, ms(300));
     37     assert(lk.owns_lock() == true);
     38     time_point t1 = Clock::now();
     39     ns d = t1 - t0 - ms(250);
     40     assert(d < ms(50));  // within 50ms
     41 }
     42 
     43 void f2()
     44 {
     45     time_point t0 = Clock::now();
     46     std::shared_lock<std::shared_timed_mutex> lk(m, ms(250));
     47     assert(lk.owns_lock() == false);
     48     time_point t1 = Clock::now();
     49     ns d = t1 - t0 - ms(250);
     50     assert(d < ms(50));  // within 50ms
     51 }
     52 
     53 #endif  // _LIBCPP_STD_VER > 11
     54 
     55 int main()
     56 {
     57 #if _LIBCPP_STD_VER > 11
     58     {
     59         m.lock();
     60         std::vector<std::thread> v;
     61         for (int i = 0; i < 5; ++i)
     62             v.push_back(std::thread(f1));
     63         std::this_thread::sleep_for(ms(250));
     64         m.unlock();
     65         for (auto& t : v)
     66             t.join();
     67     }
     68     {
     69         m.lock();
     70         std::vector<std::thread> v;
     71         for (int i = 0; i < 5; ++i)
     72             v.push_back(std::thread(f2));
     73         std::this_thread::sleep_for(ms(300));
     74         m.unlock();
     75         for (auto& t : v)
     76             t.join();
     77     }
     78 #endif  // _LIBCPP_STD_VER > 11
     79 }
     80