libcxx

libcxx mirror with random patches
git clone https://git.neptards.moe/neptards/libcxx.git
Log | Files | Refs

mutex_try_to_lock.pass.cpp (1794B)


      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++98, c++03, c++11
     12 
     13 // FLAKY_TEST
     14 
     15 // <shared_mutex>
     16 
     17 // template <class Mutex> class shared_lock;
     18 
     19 // shared_lock(mutex_type& m, try_to_lock_t);
     20 
     21 #include <shared_mutex>
     22 #include <thread>
     23 #include <vector>
     24 #include <cstdlib>
     25 #include <cassert>
     26 
     27 std::shared_timed_mutex m;
     28 
     29 typedef std::chrono::system_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 void f()
     36 {
     37     time_point t0 = Clock::now();
     38     {
     39         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     40         assert(lk.owns_lock() == false);
     41     }
     42     {
     43         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     44         assert(lk.owns_lock() == false);
     45     }
     46     {
     47         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     48         assert(lk.owns_lock() == false);
     49     }
     50     while (true)
     51     {
     52         std::shared_lock<std::shared_timed_mutex> lk(m, std::try_to_lock);
     53         if (lk.owns_lock())
     54             break;
     55     }
     56     time_point t1 = Clock::now();
     57     ns d = t1 - t0 - ms(250);
     58     assert(d < ms(200));  // within 200ms
     59 }
     60 
     61 int main()
     62 {
     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 }