• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 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 HISTREAMER_FOUNDATION_OSAL_AUTO_SPIN_LOCK_H
17 #define HISTREAMER_FOUNDATION_OSAL_AUTO_SPIN_LOCK_H
18 
19 #include <atomic>
20 
21 namespace OHOS {
22 namespace Media {
23 
24     class SpinLock {
25     public:
test_and_set(std::memory_order order)26         bool test_and_set(std::memory_order order)
27         {
28             return spinLock_.test_and_set(order);
29         }
30 
clear(std::memory_order order)31         void clear(std::memory_order order)
32         {
33             spinLock_.clear(order);
34         }
35 
36     private:
37         std::atomic_flag spinLock_ = ATOMIC_FLAG_INIT;
38     };
39 
40     class AutoSpinLock {
41     public:
AutoSpinLock(SpinLock & spinLock)42         explicit AutoSpinLock(SpinLock& spinLock)
43             : spinLock_(spinLock)
44         {
45             while (spinLock_.test_and_set(std::memory_order_acquire));
46         }
47 
48         AutoSpinLock(const AutoSpinLock&) = delete;
49 
50         AutoSpinLock& operator=(const AutoSpinLock&) = delete;
51 
~AutoSpinLock()52         ~AutoSpinLock()
53         {
54             spinLock_.clear(std::memory_order_release);
55         }
56 
57     private:
58         SpinLock& spinLock_;
59     };
60 
61 } // namespace Media
62 } // namespace OHOS
63 
64 #endif // HISTREAMER_FOUNDATION_OSAL_AUTO_SPIN_LOCK_H
65