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 // template <class Mutex> class shared_lock;
     13 
     14 // shared_lock(mutex_type& m, try_to_lock_t);
     15 
     16 #include <shared_mutex>
     17 #include <thread>
     18 #include <vector>
     19 #include <cstdlib>
     20 #include <cassert>
     21 
     22 #if _LIBCPP_STD_VER > 11
     23 
     24 std::shared_timed_mutex m;
     25 
     26 typedef std::chrono::system_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 f()
     33 {
     34     time_point t0 = Clock::now();
     35     {
     36         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     37         assert(lk.owns_lock() == false);
     38     }
     39     {
     40         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     41         assert(lk.owns_lock() == false);
     42     }
     43     {
     44         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     45         assert(lk.owns_lock() == false);
     46     }
     47     while (true)
     48     {
     49         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     50         if (lk.owns_lock())
     51             break;
     52     }
     53     time_point t1 = Clock::now();
     54     ns d = t1 - t0 - ms(250);
     55     assert(d < ms(200));  // within 200ms
     56 }
     57 
     58 #endif  // _LIBCPP_STD_VER > 11
     59 
     60 int main()
     61 {
     62 #if _LIBCPP_STD_VER > 11
     63     m.lock();
     64     std::vector<std::thread> v;
     65     for (int i = 0; i < 5; ++i)
     66         v.push_back(std::thread(f));
     67     std::this_thread::sleep_for(ms(250));
     68     m.unlock();
     69     for (auto& t : v)
     70         t.join();
     71 #endif  // _LIBCPP_STD_VER > 11
     72 }
     73