Home | History | Annotate | Download | only in thread.lock.shared.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 // <shared_mutex>
     11 
     12 // template <class Mutex> class shared_lock;
     13 
     14 // bool try_lock();
     15 
     16 #include <shared_mutex>
     17 #include <cassert>
     18 
     19 #if _LIBCPP_STD_VER > 11
     20 
     21 bool try_lock_called = false;
     22 
     23 struct mutex
     24 {
     25     bool try_lock_shared()
     26     {
     27         try_lock_called = !try_lock_called;
     28         return try_lock_called;
     29     }
     30     void unlock_shared() {}
     31 };
     32 
     33 mutex m;
     34 
     35 #endif  // _LIBCPP_STD_VER > 11
     36 
     37 int main()
     38 {
     39 #if _LIBCPP_STD_VER > 11
     40     std::shared_lock<mutex> lk(m, std::defer_lock);
     41     assert(lk.try_lock() == true);
     42     assert(try_lock_called == true);
     43     assert(lk.owns_lock() == true);
     44     try
     45     {
     46         lk.try_lock();
     47         assert(false);
     48     }
     49     catch (std::system_error& e)
     50     {
     51         assert(e.code().value() == EDEADLK);
     52     }
     53     lk.unlock();
     54     assert(lk.try_lock() == false);
     55     assert(try_lock_called == false);
     56     assert(lk.owns_lock() == false);
     57     lk.release();
     58     try
     59     {
     60         lk.try_lock();
     61         assert(false);
     62     }
     63     catch (std::system_error& e)
     64     {
     65         assert(e.code().value() == EPERM);
     66     }
     67 #endif  // _LIBCPP_STD_VER > 11
     68 }
     69