vibe.d beta banner
get vibe.d

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

Function lock

Locks the given shared object and returns a ScopedLock for accessing any unshared members.

ScopedLock!T lock(T) (
  shared(T) object
) pure nothrow @safe;

void lock(T) (
  shared(T) object,
  scope void delegate(scope T) accessor
) nothrow;

void lock(T) (
  shared(T) object,
  scope void delegate(scope T) accessor

Using this function will ensure that there are no data races. For this reason, the class type T is required to contain no unshared or unisolated aliasing.

See Also



import vibe.core.concurrency;

static class Item {
	private double m_value;

	this(double value) pure { m_value = value; }

	@property double value() const pure { return m_value; }

static class Manager {
	private {
		string m_name;
		Isolated!(Item) m_ownedItem;
		Isolated!(shared(Item)[]) m_items;

	pure this(string name)
		m_name = name;
		auto itm = makeIsolated!Item(3.5);
		m_ownedItem = itm.move;

	void addItem(shared(Item) item) pure { m_items ~= item; }

	double getTotalValue()
	const pure {
		double sum = 0;

		// lock() is required to access shared objects
		foreach (itm; m_items) {
			auto l = itm.lock();
			sum += l.value;

		// owned objects can be accessed without locking
		sum += m_ownedItem.value;

		return sum;

void test()
	import std.stdio;

	auto man = cast(shared)new Manager("My manager");
		auto l = man.lock();
		l.addItem(new shared(Item)(1.5));
		l.addItem(new shared(Item)(0.5));

	writefln("Total value: %s", man.lock().getTotalValue());

Sönke Ludwig


© 2013-2014 Sönke Ludwig


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