vibe.d beta banner
get vibe.d
0.7.29

Function lock

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

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.

Prototypes

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

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

See Also

core.concurrency.isWeaklyIsolated

Example

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.unsafeGet) {
			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());
}
Authors

Sönke Ludwig

Copyright

© 2013-2016 RejectedSoftware e.K.

License

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