[dmd-concurrency] draft 7

Michel Fortin michel.fortin at michelf.com
Mon Feb 1 14:40:17 PST 2010


Le 2010-02-01 à 17:16, Andrei Alexandrescu a écrit :

> Michel Fortin wrote:
>> Le 2010-02-01 à 16:49, Andrei Alexandrescu a écrit :
>>> I think swap could be typed as:
>>> 
>>> swap(scope ref int[], scope ref int[]);
>>> 
>>> The point of scope parameter typechecking is that swap does not save a reference surreptitiously; I think escaping to another scope parameter should be fine (if somewhat conservative).
>> It's not safe unless the compiler enforcse that all scoped parameters belong to the same owner object. Otherwise you could exchange them between too different objects and unless there is no aliasing they'd now each be owned by two locks!
> 
> Could you please give an example?

Sure. Here is a List class, each item being a reference to unsynchronized objects. (Items could be anything with a reference or a pointer.)

	class Item { // not synchronized
		string name;
		int quantity;
	}

	synchronized class List {
		Item[] all;
		Item current;

		this() {
			all = new Item[5];
			foreach (ref item; all) {
				all = new Item();
			}
			current = all[0];
		}
	}

Now run this code:

	List list1 = new List();
	List list2 = new List();
	
	synchronized (this, other) {
		swap(this.current, other.current);
	}

This makes each class take the current item of the other, but at the same time keeping a reference in its 'all' array. Synchronizing with either one of the List could give you access to the swapped items, so it could result in two threads accessing it at the same time.

So you should get an error when calling swap here:

	synchronized (this, other) {
		swap(this.current, other.current);
		// Error! this.current and other.current are not protected by the
		// same lock.
	}

The compiler need to know 'swap' wants the owner of the two variables to be the same, so either all 'scope' arguments are said to have the same owner, or we have a way to make two argument have the same scope, perhaps by giving each scope a name or a number: 'scope!1'.


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/





More information about the dmd-concurrency mailing list