Locks & Synchronization Manual
Locks are used to guard access to resources that are shared across multiple threads.
maxon::Spinlock implements a mutex that will loop on a pause/idle instruction when it is already locked.
// lock g_spinlock. 锁 ();
// handle shared resource const maxon::Result<void> res = UpdateGlobalData();
// unlock g_spinlock. Unlock ();
A maxon::ScopedLock acquires a lock when created and releases upon destruction (at the end of the scope).
// lock on creation maxon::ScopedLock scopedLock(lock);
// handle shared resource return UpdateGlobalData(); }
The maxon::RWSpinlock allows access for multiple readers and only one exclusive writer.
// example global instance; typically a member variable would be used static maxon::RWSpinlock g_rwSpinlock; static maxon::Result<void> UpdateWithRWLock() { // write lock g_rwSpinlock. WriteLock ();
// handle shared resource const maxon::Result<void> res = UpdateGlobalData();
// write unlock g_rwSpinlock. WriteUnlock (); return res; } static maxon::Int ReadWithRWLock( maxon::Int i) { // read lock g_rwSpinlock. ReadLock ();
// access shared resource const maxon::Int res = AccessData(i);
// read unlock g_rwSpinlock. ReadUnlock (); return res; }
The maxon::ARWLock is an asymmetric read write lock which prefers the readers.
// example global instance; typically a member variable would be used static maxon::ARWLock * g_arwlock = nullptr ; static maxon::Result<void> Init() { iferr_scope ; g_arwlock = NewObj ( maxon::ARWLock ) iferr_return ; return maxon::OK ; } static void Clear() { DeleteObj (g_arwlock); } MAXON_INITIALIZATION (Init, Clear); static maxon::Result<void> UpdateWithARWLock() { g_arwlock-> WriteLock (); const maxon::Result<void> res = UpdateGlobalData(); g_arwlock-> WriteUnlock (); return res; }
The maxon::Synchronized template is used to guarantee safe access to a given variable. It allows access to the variable only after a lock has been acquired. For asymmetric read-write access there is also maxon::RWSynchronized based on maxon::ARWLock .
// get locked pointer to get write access auto lockedPtr = _string.Write(); for ( maxon::String & str : strings) { lockedPtr->Append(str) iferr_return ; }
// lock on _string is released when the function scope is left return maxon::OK ; } private : maxon::Synchronized<maxon::String> _string; };
The maxon::Serializer guarantees mutually exclusive access to a shared resource. The given lambdas are enqueued and executed.