1 /*
2  * Copyright (c) 2023 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  /**
17  * @file mutex.h
18  *
19  * @brief Declares the mutex interfaces in C++.
20  *
21  * @since 10
22  * @version 1.0
23  */
24 #ifndef FFRT_API_CPP_MUTEX_H
25 #define FFRT_API_CPP_MUTEX_H
26 #include "c/mutex.h"
27 
28 namespace ffrt {
29 class mutex : public ffrt_mutex_t {
30 public:
mutex()31     mutex()
32     {
33         ffrt_mutex_init(this, nullptr);
34     }
35 
~mutex()36     ~mutex()
37     {
38         ffrt_mutex_destroy(this);
39     }
40 
41     mutex(mutex const&) = delete;
42     void operator=(mutex const&) = delete;
43 
try_lock()44     inline bool try_lock()
45     {
46         return ffrt_mutex_trylock(this) == ffrt_success ? true : false;
47     }
48 
lock()49     inline void lock()
50     {
51         ffrt_mutex_lock(this);
52     }
53 
unlock()54     inline void unlock()
55     {
56         ffrt_mutex_unlock(this);
57     }
58 };
59 
60 class recursive_mutex : public ffrt_mutex_t {
61 public:
recursive_mutex()62     recursive_mutex()
63     {
64         ffrt_mutexattr_init(&attr);
65         ffrt_mutexattr_settype(&attr, ffrt_mutex_recursive);
66         ffrt_mutex_init(this, &attr);
67     }
68 
~recursive_mutex()69     ~recursive_mutex()
70     {
71         ffrt_mutexattr_destroy(&attr);
72         ffrt_mutex_destroy(this);
73     }
74 
75     recursive_mutex(recursive_mutex const&) = delete;
76     void operator=(recursive_mutex const&) = delete;
77 
try_lock()78     inline bool try_lock()
79     {
80         return ffrt_mutex_trylock(this) == ffrt_success ? true : false;
81     }
82 
lock()83     inline void lock()
84     {
85         ffrt_mutex_lock(this);
86     }
87 
unlock()88     inline void unlock()
89     {
90         ffrt_mutex_unlock(this);
91     }
92 private:
93     ffrt_mutexattr_t attr;
94 };
95 } // namespace ffrt
96 #endif
97