Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 :
11 : #ifndef HCCL_SPIN_MUTEX_H
12 : #define HCCL_SPIN_MUTEX_H
13 :
14 : #include <mutex>
15 : #include <atomic>
16 :
17 : namespace hccl {
18 :
19 : class SpinMutex {
20 : public:
21 2 : SpinMutex() = default;
22 : ~SpinMutex() = default;
23 : // delete copy and move constructors and assign operators
24 : SpinMutex(SpinMutex const&) = delete; // Copy construct
25 : SpinMutex(SpinMutex&&) = delete; // Move construct
26 : SpinMutex& operator=(SpinMutex const&) = delete; // Copy assign
27 : SpinMutex& operator=(SpinMutex&&) = delete; // Move assign
28 2 : void lock()
29 : {
30 2 : bool expected = false;
31 2 : while (!flag.compare_exchange_strong(expected, true)) {
32 0 : expected = false;
33 : }
34 2 : }
35 2 : void unlock() { flag.store(false); }
36 :
37 : private:
38 : std::atomic<bool> flag = ATOMIC_VAR_INIT(false);
39 : };
40 : } // namespace hccl
41 : #endif // HCCL_SPIN_MUTEX_H
|