Path: blob/master/thirdparty/embree/common/sys/mutex.h
9912 views
// Copyright 2009-2021 Intel Corporation1// SPDX-License-Identifier: Apache-2.023#pragma once45#include "platform.h"6#include "intrinsics.h"7#include "atomic.h"89#define CPU_CACHELINE_SIZE 6410namespace embree11{12/*! system mutex */13class MutexSys {14friend struct ConditionImplementation;15public:16MutexSys();17~MutexSys();1819private:20MutexSys (const MutexSys& other) DELETED; // do not implement21MutexSys& operator= (const MutexSys& other) DELETED; // do not implement2223public:24void lock();25bool try_lock();26void unlock();2728protected:29void* mutex;30};3132/*! spinning mutex */33class SpinLock34{35public:3637SpinLock ()38: flag(false) {}3940__forceinline bool isLocked() {41return flag.load();42}4344__forceinline void lock()45{46while (true)47{48while (flag.load())49{50_mm_pause();51_mm_pause();52}5354bool expected = false;55if (flag.compare_exchange_strong(expected,true,std::memory_order_acquire))56break;57}58}5960__forceinline bool try_lock()61{62bool expected = false;63if (flag.load() != expected) {64return false;65}66return flag.compare_exchange_strong(expected,true,std::memory_order_acquire);67}6869__forceinline void unlock() {70flag.store(false,std::memory_order_release);71}7273__forceinline void wait_until_unlocked()74{75while(flag.load())76{77_mm_pause();78_mm_pause();79}80}8182public:83atomic<bool> flag;84};8586class PaddedSpinLock : public SpinLock87{88private:89MAYBE_UNUSED char padding[CPU_CACHELINE_SIZE - sizeof(SpinLock)];90};91/*! safe mutex lock and unlock helper */92template<typename Mutex> class Lock {93public:94Lock (Mutex& mutex) : mutex(mutex), locked(true) { mutex.lock(); }95Lock (Mutex& mutex, bool locked) : mutex(mutex), locked(locked) {}96~Lock() { if (locked) mutex.unlock(); }97__forceinline void lock() { assert(!locked); locked = true; mutex.lock(); }98__forceinline bool isLocked() const { return locked; }99protected:100Mutex& mutex;101bool locked;102};103}104105106