Function createMonitor
Creates a new monitor primitive for type T
.
Example
import core .thread : Thread;
import std .algorithm .iteration : sum;
import vibe .core .core : runWorkerTaskH;
shared items = createMonitor!(int[])(new Mutex);
// Run 64 tasks with read-modify-write operations that would
// quickly lead to race-conditions if performed unprotected
Task[64] tasks;
foreach (i; 0 .. tasks .length) {
tasks[i] = runWorkerTaskH((shared(Monitor!(int[], Mutex))* itms) nothrow {
// The monitor ensures that all access to the data
// is protected by the mutex
auto litems = itms .lock();
auto newentry = sum(litems[]) + 1;
Thread .sleep(10 .msecs);
litems ~= newentry;
}, &items);
}
// finish up all tasks
foreach (t; tasks) t .joinUninterruptible();
// verify that the results are as expected
auto litms = items .lock();
assert(litms .length == tasks .length);
foreach (idx, i; litms)
assert(i == sum(litms[0 .. idx]) + 1);