vibe.d beta banner
get vibe.d
0.10.1

Asynchronous I/O that doesn’t get in your way, written in D

Function createMonitor

Creates a new monitor primitive for type T.

shared(Monitor!(T,M)) createMonitor(T, M) (
  M mutex
) @trusted;

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);
Authors

Leonid Kramer, Sönke Ludwig, Manuel Frischknecht

Copyright

© 2012-2019 Sönke Ludwig

License

Subject to the terms of the MIT license, as written in the included LICENSE.txt file.