1 /* 2 Copyright (c) 2021-2023 Intel Corporation 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 #ifndef __TBB_mutex_H 18 #define __TBB_mutex_H 19 20 #include "detail/_namespace_injection.h" 21 #include "detail/_utils.h" 22 #include "detail/_scoped_lock.h" 23 #include "detail/_waitable_atomic.h" 24 #include "detail/_mutex_common.h" 25 #include "profiling.h" 26 27 namespace tbb { 28 namespace detail { 29 namespace d1 { 30 31 class mutex { 32 public: 33 //! Constructors mutex()34 mutex() { 35 create_itt_sync(this, "tbb::mutex", ""); 36 }; 37 38 //! Destructor 39 ~mutex() = default; 40 41 //! No Copy 42 mutex(const mutex&) = delete; 43 mutex& operator=(const mutex&) = delete; 44 45 using scoped_lock = unique_scoped_lock<mutex>; 46 47 //! Mutex traits 48 static constexpr bool is_rw_mutex = false; 49 static constexpr bool is_recursive_mutex = false; 50 static constexpr bool is_fair_mutex = false; 51 52 //! Acquire lock 53 /** Spin if the lock is taken */ lock()54 void lock() { 55 call_itt_notify(prepare, this); 56 while (!try_lock()) { 57 my_flag.wait(true, /* context = */ 0, std::memory_order_relaxed); 58 } 59 } 60 61 //! Try acquiring lock (non-blocking) 62 /** Return true if lock acquired; false otherwise. */ try_lock()63 bool try_lock() { 64 bool result = !my_flag.load(std::memory_order_relaxed) && !my_flag.exchange(true); 65 if (result) { 66 call_itt_notify(acquired, this); 67 } 68 return result; 69 } 70 71 //! Release lock unlock()72 void unlock() { 73 call_itt_notify(releasing, this); 74 // We need Write Read memory barrier before notify that reads the waiter list. 75 // In C++ only full fence covers this type of barrier. 76 my_flag.exchange(false); 77 my_flag.notify_one_relaxed(); 78 } 79 80 private: 81 waitable_atomic<bool> my_flag{0}; 82 }; // class mutex 83 84 } // namespace d1 85 } // namespace detail 86 87 inline namespace v1 { 88 using detail::d1::mutex; 89 } // namespace v1 90 91 } // namespace tbb 92 93 #endif // __TBB_mutex_H 94