1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #ifndef LLVM_SUPPORT_ADVISORYLOCK_H 10 #define LLVM_SUPPORT_ADVISORYLOCK_H 11 12 #include "llvm/Support/Error.h" 13 14 #include <chrono> 15 16 namespace llvm { 17 /// Describes the result of waiting for the owner to release the lock. 18 enum class WaitForUnlockResult { 19 /// The lock was released successfully. 20 Success, 21 /// Owner died while holding the lock. 22 OwnerDied, 23 /// Reached timeout while waiting for the owner to release the lock. 24 Timeout, 25 }; 26 27 /// A synchronization primitive with weak mutual exclusion guarantees. 28 /// Implementations of this interface may allow multiple threads/processes to 29 /// acquire the ownership of the lock simultaneously. 30 /// Typically, threads/processes waiting for the lock to be unlocked will 31 /// validate that the computation was performed by the expected thread/process 32 /// and re-run the computation if not. 33 class AdvisoryLock { 34 public: 35 /// Tries to acquire ownership of the lock without blocking. 36 /// 37 /// \returns true if ownership of the lock was acquired successfully, false if 38 /// the lock is already owned by someone else, or \c Error in case of an 39 /// unexpected failure. 40 virtual Expected<bool> tryLock() = 0; 41 42 /// For a lock owned by someone else, wait until it is unlocked. 43 /// 44 /// \param MaxSeconds the maximum total wait time in seconds. 45 virtual WaitForUnlockResult 46 waitForUnlockFor(std::chrono::seconds MaxSeconds) = 0; 47 48 /// For a lock owned by someone else, unlock it. A permitted side-effect is 49 /// that another thread/process may acquire ownership of the lock before the 50 /// existing owner unlocks it. This is an unsafe operation. 51 virtual std::error_code unsafeMaybeUnlock() = 0; 52 53 /// Unlocks the lock if its ownership was previously acquired by \c tryLock(). 54 virtual ~AdvisoryLock() = default; 55 }; 56 } // end namespace llvm 57 58 #endif 59