1// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#ifndef sw_RecursiveLock_hpp
16#define sw_RecursiveLock_hpp
17
18#include "Thread.hpp"
19
20#include <mutex>
21
22namespace sw
23{
24 class RecursiveLock
25 {
26 public:
27 RecursiveLock()
28 {
29 }
30
31 bool attemptLock()
32 {
33 return mutex.try_lock();
34 }
35
36 void lock()
37 {
38 mutex.lock();
39 }
40
41 void unlock()
42 {
43 mutex.unlock();
44 }
45 private:
46 std::recursive_mutex mutex;
47 };
48}
49
50class RecursiveLockGuard
51{
52public:
53 explicit RecursiveLockGuard(sw::RecursiveLock &mutex) : mutex(&mutex)
54 {
55 mutex.lock();
56 }
57
58 explicit RecursiveLockGuard(sw::RecursiveLock *mutex) : mutex(mutex)
59 {
60 if (mutex) mutex->lock();
61 }
62
63 ~RecursiveLockGuard()
64 {
65 if (mutex) mutex->unlock();
66 }
67
68protected:
69 sw::RecursiveLock *mutex;
70};
71
72#endif // sw_RecursiveLock_hpp
73