1 //===-- runtime/lock.h ------------------------------------------*- C++ -*-===// 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 // Wraps a mutex 10 11 #ifndef FORTRAN_RUNTIME_LOCK_H_ 12 #define FORTRAN_RUNTIME_LOCK_H_ 13 14 #include "terminator.h" 15 #include <mutex> 16 17 namespace Fortran::runtime { 18 19 class Lock { 20 public: 21 void Take() { mutex_.lock(); } 22 bool Try() { return mutex_.try_lock(); } 23 void Drop() { mutex_.unlock(); } 24 void CheckLocked(const Terminator &terminator) { 25 if (Try()) { 26 Drop(); 27 terminator.Crash("Lock::CheckLocked() failed"); 28 } 29 } 30 31 private: 32 std::mutex mutex_; 33 }; 34 35 class CriticalSection { 36 public: 37 explicit CriticalSection(Lock &lock) : lock_{lock} { lock_.Take(); } 38 ~CriticalSection() { lock_.Drop(); } 39 40 private: 41 Lock &lock_; 42 }; 43 } // namespace Fortran::runtime 44 45 #endif // FORTRAN_RUNTIME_LOCK_H_ 46