1 /**
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
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
16 #include "runtime/include/locks.h"
17 #include "libpandabase/utils/logger.h"
18 #include "include/thread.h"
19
20 #include <memory>
21
22 namespace panda {
23
24 static bool is_initialized = false;
25
26 MutatorLock *Locks::mutator_lock = nullptr;
27 os::memory::Mutex *Locks::custom_tls_lock = nullptr;
28 os::memory::Mutex *Locks::user_suspension_lock = nullptr;
29
Initialize()30 void Locks::Initialize()
31 {
32 if (!is_initialized) {
33 Locks::mutator_lock = new MutatorLock();
34 Locks::custom_tls_lock = new os::memory::Mutex();
35 Locks::user_suspension_lock = new os::memory::Mutex();
36 is_initialized = true;
37 }
38 }
39
40 #ifndef NDEBUG
41
ReadLock()42 void MutatorLock::ReadLock()
43 {
44 ASSERT(!HasLock());
45 os::memory::RWLock::ReadLock();
46 LOG(DEBUG, RUNTIME) << "MutatorLock::ReadLock";
47 Thread::GetCurrent()->SetLockState(RDLOCK);
48 }
49
WriteLock()50 void MutatorLock::WriteLock()
51 {
52 ASSERT(!HasLock());
53 os::memory::RWLock::WriteLock();
54 LOG(DEBUG, RUNTIME) << "MutatorLock::WriteLock";
55 Thread::GetCurrent()->SetLockState(WRLOCK);
56 }
57
TryReadLock()58 bool MutatorLock::TryReadLock()
59 {
60 bool ret = os::memory::RWLock::TryReadLock();
61 LOG(DEBUG, RUNTIME) << "MutatorLock::TryReadLock";
62 if (ret) {
63 Thread::GetCurrent()->SetLockState(RDLOCK);
64 }
65 return ret;
66 }
67
TryWriteLock()68 bool MutatorLock::TryWriteLock()
69 {
70 bool ret = os::memory::RWLock::TryWriteLock();
71 LOG(DEBUG, RUNTIME) << "MutatorLock::TryWriteLock";
72 if (ret) {
73 Thread::GetCurrent()->SetLockState(WRLOCK);
74 }
75 return ret;
76 }
77
Unlock()78 void MutatorLock::Unlock()
79 {
80 ASSERT(HasLock());
81 os::memory::RWLock::Unlock();
82 LOG(DEBUG, RUNTIME) << "MutatorLock::Unlock";
83 Thread::GetCurrent()->SetLockState(UNLOCKED);
84 }
85
GetState()86 MutatorLock::MutatorLockState MutatorLock::GetState()
87 {
88 return Thread::GetCurrent()->GetLockState();
89 }
90
HasLock()91 bool MutatorLock::HasLock()
92 {
93 auto state = Thread::GetCurrent()->GetLockState();
94 return state == RDLOCK || state == WRLOCK;
95 }
96 #endif // !NDEBUG
97
98 } // namespace panda
99