libcxx

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

try_lock_shared.pass.cpp (1525B)


      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 // class shared_timed_mutex;
     18 
     19 // bool try_lock_shared();
     20 
     21 #include <shared_mutex>
     22 #include <thread>
     23 #include <vector>
     24 #include <cstdlib>
     25 #include <cassert>
     26 
     27 #include "test_macros.h"
     28 
     29 std::shared_timed_mutex m;
     30 
     31 typedef std::chrono::system_clock Clock;
     32 typedef Clock::time_point time_point;
     33 typedef Clock::duration duration;
     34 typedef std::chrono::milliseconds ms;
     35 typedef std::chrono::nanoseconds ns;
     36 
     37 
     38 #if !defined(TEST_HAS_SANITIZERS)
     39 ms Tolerance = ms(200);
     40 #else
     41 ms Tolerance = ms(200 * 5);
     42 #endif
     43 
     44 void f()
     45 {
     46     time_point t0 = Clock::now();
     47     assert(!m.try_lock_shared());
     48     assert(!m.try_lock_shared());
     49     assert(!m.try_lock_shared());
     50     while(!m.try_lock_shared())
     51         ;
     52     time_point t1 = Clock::now();
     53     m.unlock_shared();
     54     ns d = t1 - t0 - ms(250);
     55     assert(d < Tolerance);  // within tolerance
     56 }
     57 
     58 int main()
     59 {
     60     m.lock();
     61     std::vector<std::thread> v;
     62     for (int i = 0; i < 5; ++i)
     63         v.push_back(std::thread(f));
     64     std::this_thread::sleep_for(ms(250));
     65     m.unlock();
     66     for (auto& t : v)
     67         t.join();
     68 }