From 6c0bdf2976c5d7b876adf3e5271c17c552d9d571 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Ludwig?= Date: Mon, 14 Jan 2019 00:14:04 +0100 Subject: [PATCH] Add documentation and unittest example to scopedMutexLock. --- source/vibe/core/sync.d | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/source/vibe/core/sync.d b/source/vibe/core/sync.d index f2fdef5..3b6aec2 100644 --- a/source/vibe/core/sync.d +++ b/source/vibe/core/sync.d @@ -33,12 +33,42 @@ shared(ManualEvent) createSharedManualEvent() return shared(ManualEvent).init; } + +/** Performs RAII based locking/unlocking of a mutex. + + Note that while `TaskMutex` can be used with D's built-in `synchronized` + statement, `InterruptibleTaskMutex` cannot. This function provides a + library based alternative that is suitable for use with all mutex types. +*/ ScopedMutexLock!M scopedMutexLock(M)(M mutex, LockMode mode = LockMode.lock) if (is(M : Mutex) || is(M : Lockable)) { return ScopedMutexLock!M(mutex, mode); } +/// +unittest { + import vibe.core.core : runWorkerTaskH; + + __gshared int counter; + __gshared InterruptibleTaskMutex mutex; + + mutex = new InterruptibleTaskMutex; + + Task[] tasks; + + foreach (i; 0 .. 100) { + tasks ~= runWorkerTaskH({ + auto l = scopedMutexLock(mutex); + counter++; + }); + } + + foreach (t; tasks) t.join(); + + assert(counter == 100); +} + unittest { scopedMutexLock(new Mutex); scopedMutexLock(new TaskMutex);