libcxx

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

mutex_try_to_lock.pass.cpp (1541B)


      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 
     12 // <mutex>
     13 
     14 // template <class Mutex> class unique_lock;
     15 
     16 // unique_lock(mutex_type& m, try_to_lock_t);
     17 
     18 #include <mutex>
     19 #include <thread>
     20 #include <cstdlib>
     21 #include <cassert>
     22 
     23 std::mutex m;
     24 
     25 typedef std::chrono::system_clock Clock;
     26 typedef Clock::time_point time_point;
     27 typedef Clock::duration duration;
     28 typedef std::chrono::milliseconds ms;
     29 typedef std::chrono::nanoseconds ns;
     30 
     31 void f()
     32 {
     33     time_point t0 = Clock::now();
     34     {
     35         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
     36         assert(lk.owns_lock() == false);
     37     }
     38     {
     39         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
     40         assert(lk.owns_lock() == false);
     41     }
     42     {
     43         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
     44         assert(lk.owns_lock() == false);
     45     }
     46     while (true)
     47     {
     48         std::unique_lock<std::mutex> lk(m, std::try_to_lock);
     49         if (lk.owns_lock())
     50             break;
     51     }
     52     time_point t1 = Clock::now();
     53     ns d = t1 - t0 - ms(250);
     54     assert(d < ms(200));  // within 200ms
     55 }
     56 
     57 int main()
     58 {
     59     m.lock();
     60     std::thread t(f);
     61     std::this_thread::sleep_for(ms(250));
     62     m.unlock();
     63     t.join();
     64 }