1 /* 2 Copyright (c) 2021 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 34 mutex() { 35 create_itt_sync(this, "tbb::mutex", ""); 36 }; 37 38 //! Destructor 39 ~mutex() { 40 __TBB_ASSERT(!my_flag.load(std::memory_order_relaxed), "destruction of an acquired mutex"); 41 } 42 43 //! No Copy 44 mutex(const mutex&) = delete; 45 mutex& operator=(const mutex&) = delete; 46 47 using scoped_lock = unique_scoped_lock<mutex>; 48 49 //! Mutex traits 50 static constexpr bool is_rw_mutex = false; 51 static constexpr bool is_recursive_mutex = false; 52 static constexpr bool is_fair_mutex = false; 53 54 //! Acquire lock 55 /** Spin if the lock is taken */ 56 void lock() { 57 call_itt_notify(prepare, this); 58 while (!try_lock()) { 59 my_flag.wait(true, /* context = */ 0, std::memory_order_relaxed); 60 } 61 } 62 63 //! Try acquiring lock (non-blocking) 64 /** Return true if lock acquired; false otherwise. */ 65 bool try_lock() { 66 bool result = !my_flag.load(std::memory_order_relaxed) && !my_flag.exchange(true); 67 if (result) { 68 call_itt_notify(acquired, this); 69 } 70 return result; 71 } 72 73 //! Release lock 74 void unlock() { 75 call_itt_notify(releasing, this); 76 // We need Write Read memory barrier before notify that reads the waiter list. 77 // In C++ only full fence covers this type of barrier. 78 my_flag.exchange(false); 79 my_flag.notify_one_relaxed(); 80 } 81 82 private: 83 waitable_atomic<bool> my_flag{0}; 84 }; // class mutex 85 86 } // namespace d1 87 } // namespace detail 88 89 inline namespace v1 { 90 using detail::d1::mutex; 91 } // namespace v1 92 93 } // namespace tbb 94 95 #endif // __TBB_mutex_H 96