Home | History | Annotate | Download | only in thread.lock.unique.locking
      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 // template <class Rep, class Period>
     17 //   bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
     18 
     19 #include <mutex>
     20 #include <cassert>
     21 
     22 #include "test_macros.h"
     23 
     24 bool try_lock_for_called = false;
     25 
     26 typedef std::chrono::milliseconds ms;
     27 
     28 struct mutex
     29 {
     30     template <class Rep, class Period>
     31         bool try_lock_for(const std::chrono::duration<Rep, Period>& rel_time)
     32     {
     33         assert(rel_time == ms(5));
     34         try_lock_for_called = !try_lock_for_called;
     35         return try_lock_for_called;
     36     }
     37     void unlock() {}
     38 };
     39 
     40 mutex m;
     41 
     42 int main()
     43 {
     44     std::unique_lock<mutex> lk(m, std::defer_lock);
     45     assert(lk.try_lock_for(ms(5)) == true);
     46     assert(try_lock_for_called == true);
     47     assert(lk.owns_lock() == true);
     48 #ifndef TEST_HAS_NO_EXCEPTIONS
     49     try
     50     {
     51         TEST_IGNORE_NODISCARD lk.try_lock_for(ms(5));
     52         assert(false);
     53     }
     54     catch (std::system_error& e)
     55     {
     56         assert(e.code().value() == EDEADLK);
     57     }
     58 #endif
     59     lk.unlock();
     60     assert(lk.try_lock_for(ms(5)) == false);
     61     assert(try_lock_for_called == false);
     62     assert(lk.owns_lock() == false);
     63     lk.release();
     64 #ifndef TEST_HAS_NO_EXCEPTIONS
     65     try
     66     {
     67         TEST_IGNORE_NODISCARD lk.try_lock_for(ms(5));
     68         assert(false);
     69     }
     70     catch (std::system_error& e)
     71     {
     72         assert(e.code().value() == EPERM);
     73     }
     74 #endif
     75 }
     76