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.

Examples

1 import vibe.core.concurrency;
2 
3 static class Item {
4 	private double m_value;
5 
6 	this(double value) pure { m_value = value; }
7 
8 	@property double value() const pure { return m_value; }
9 }
10 
11 static class Manager {
12 	private {
13 		string m_name;
14 		Isolated!(Item) m_ownedItem;
15 		Isolated!(shared(Item)[]) m_items;
16 	}
17 
18 	pure this(string name)
19 	{
20 		m_name = name;
21 		auto itm = makeIsolated!Item(3.5);
22 		m_ownedItem = itm.move;
23 	}
24 
25 	void addItem(shared(Item) item) pure { m_items ~= item; }
26 
27 	double getTotalValue()
28 	const pure {
29 		double sum = 0;
30 
31 		// lock() is required to access shared objects
32 		foreach (itm; m_items) {
33 			auto l = itm.lock();
34 			sum += l.value;
35 		}
36 
37 		// owned objects can be accessed without locking
38 		sum += m_ownedItem.value;
39 
40 		return sum;
41 	}
42 }
43 
44 void test()
45 {
46 	import std.stdio;
47 
48 	auto man = cast(shared)new Manager("My manager");
49 	{
50 		auto l = man.lock();
51 		l.addItem(new shared(Item)(1.5));
52 		l.addItem(new shared(Item)(0.5));
53 	}
54 
55 	writefln("Total value: %s", man.lock().getTotalValue());
56 }

See Also

core.concurrency.isWeaklyIsolated

Meta