2020-01-24 08:10:00 +08:00
|
|
|
//===-- runtime/lock.h ------------------------------------------*- C++ -*-===//
|
|
|
|
//
|
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2020-02-14 06:41:56 +08:00
|
|
|
// Wraps a mutex
|
2020-01-24 08:10:00 +08:00
|
|
|
|
|
|
|
#ifndef FORTRAN_RUNTIME_LOCK_H_
|
|
|
|
#define FORTRAN_RUNTIME_LOCK_H_
|
|
|
|
|
2020-02-14 06:41:56 +08:00
|
|
|
#include "terminator.h"
|
2020-03-05 22:52:35 +08:00
|
|
|
#include <mutex>
|
2020-01-24 08:10:00 +08:00
|
|
|
|
|
|
|
namespace Fortran::runtime {
|
|
|
|
|
|
|
|
class Lock {
|
|
|
|
public:
|
2020-03-05 22:52:35 +08:00
|
|
|
void Take() { mutex_.lock(); }
|
|
|
|
bool Try() { return mutex_.try_lock(); }
|
|
|
|
void Drop() { mutex_.unlock(); }
|
2020-02-05 08:55:45 +08:00
|
|
|
void CheckLocked(const Terminator &terminator) {
|
2020-01-24 08:10:00 +08:00
|
|
|
if (Try()) {
|
|
|
|
Drop();
|
|
|
|
terminator.Crash("Lock::CheckLocked() failed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
private:
|
2020-03-05 22:52:35 +08:00
|
|
|
std::mutex mutex_;
|
2020-01-24 08:10:00 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
class CriticalSection {
|
|
|
|
public:
|
|
|
|
explicit CriticalSection(Lock &lock) : lock_{lock} { lock_.Take(); }
|
|
|
|
~CriticalSection() { lock_.Drop(); }
|
|
|
|
|
|
|
|
private:
|
|
|
|
Lock &lock_;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif // FORTRAN_RUNTIME_LOCK_H_
|