1 //===-- runtime/lock.h ------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
11 #ifndef FORTRAN_RUNTIME_LOCK_H_
12 #define FORTRAN_RUNTIME_LOCK_H_
14 #include "terminator.h"
17 // Avoid <mutex> if possible to avoid introduction of C++ runtime
18 // library dependence.
20 #define USE_PTHREADS 1
28 #include "flang/Common/windows-include.h"
33 namespace Fortran::runtime
{
37 #if RT_USE_PSEUDO_LOCK
38 // No lock implementation, e.g. for using together
39 // with RT_USE_PSEUDO_FILE_UNIT.
40 // The users of Lock class may use it under
41 // USE_PTHREADS and otherwise, so it has to provide
42 // all the interfaces.
43 RT_API_ATTRS
void Take() {}
44 RT_API_ATTRS
bool Try() { return true; }
45 RT_API_ATTRS
void Drop() {}
46 RT_API_ATTRS
bool TakeIfNoDeadlock() { return true; }
48 Lock() { pthread_mutex_init(&mutex_
, nullptr); }
49 ~Lock() { pthread_mutex_destroy(&mutex_
); }
51 while (pthread_mutex_lock(&mutex_
)) {
53 holder_
= pthread_self();
56 bool TakeIfNoDeadlock() {
58 auto thisThread
{pthread_self()};
59 if (pthread_equal(thisThread
, holder_
)) {
66 bool Try() { return pthread_mutex_trylock(&mutex_
) == 0; }
69 pthread_mutex_unlock(&mutex_
);
72 Lock() { InitializeCriticalSection(&cs_
); }
73 ~Lock() { DeleteCriticalSection(&cs_
); }
74 void Take() { EnterCriticalSection(&cs_
); }
75 bool Try() { return TryEnterCriticalSection(&cs_
); }
76 void Drop() { LeaveCriticalSection(&cs_
); }
78 void Take() { mutex_
.lock(); }
79 bool Try() { return mutex_
.try_lock(); }
80 void Drop() { mutex_
.unlock(); }
83 void CheckLocked(const Terminator
&terminator
) {
86 terminator
.Crash("Lock::CheckLocked() failed");
91 #if RT_USE_PSEUDO_FILE_UNIT
94 pthread_mutex_t mutex_
{};
95 volatile bool isBusy_
{false};
96 volatile pthread_t holder_
;
104 class CriticalSection
{
106 explicit RT_API_ATTRS
CriticalSection(Lock
&lock
) : lock_
{lock
} {
109 RT_API_ATTRS
~CriticalSection() { lock_
.Drop(); }
114 } // namespace Fortran::runtime
116 #endif // FORTRAN_RUNTIME_LOCK_H_