1 /*
2  * Copyright (c) 2024 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 #ifndef RECORD_MUTEX_H
17 #define RECORD_MUTEX_H
18 
19 #include <sys/types.h>
20 #include <chrono>
21 #include <cstdint>
22 #include <securec.h>
23 #include "cpp/mutex.h"
24 
25 namespace ffrt {
26 enum class MutexOwnerType {
27     MUTEX_OWNER_TYPE_TASK,
28     MUTEX_OWNER_TYPE_THREAD,
29 };
30 
31 struct MutexOwner {
32     uint64_t id; // 持锁task的id或者持锁线程的id
33     MutexOwnerType type;
34     std::chrono::steady_clock::time_point timestamp;
35 };
36 
37 class RecordMutex {
38 public:
lock()39     void lock()
40     {
41         mutex_.lock();
42         LoadInfo();
43     }
44 
unlock()45     void unlock()
46     {
47         ClearInfo();
48         mutex_.unlock();
49     }
50 
GetMutex()51     mutex* GetMutex()
52     {
53         return &mutex_;
54     }
55 
HasLock()56     bool HasLock()
57     {
58         return owner_.id != 0;
59     }
60 
61     bool IsTimeout();
62 
GetOwnerId()63     uint64_t GetOwnerId()
64     {
65         return owner_.id;
66     }
67 
GetOwnerType()68     MutexOwnerType GetOwnerType()
69     {
70         return owner_.type;
71     }
72 
73     uint64_t GetDuration();
74 
75 private:
76     void LoadInfo();
77 
ClearInfo()78     void ClearInfo()
79     {
80         owner_.id = 0;
81     }
82 
83     ffrt::mutex mutex_;
84     MutexOwner owner_ = { 0 };
85 };
86 } // namespace ffrt
87 
88 #endif