[dmd-concurrency] Defining shared delegates

Michel Fortin michel.fortin at michelf.com
Tue Jan 19 15:30:50 PST 2010


Le 2010-01-19 à 17:37, Andrei Alexandrescu a écrit :

> I guess I'm misunderstanding what's going on.

Ok, I'll make it easier to digest. Here are three examples of someone creating a delegate:

	int delegate(int) func() {
		int a = 1, b = 12;
		return (int i){ return a + b; }
	}

Now, we both agree that sharing this delegate shouldn't be allowed. The returned delegate makes use of thread-local mutable variables which is obviously not thread-safe.

Next one:

	int delegate(int) func() {
		immutable int a = 1, b = 12;
		return (int i){ return a*i + b; }
	}

This example is identical to the first, but the delegate uses only immutable variables from the outer context. Because of this, this delegate is safe to share between thread. Do we agree?

Well, if we agree we can probably agree that this one too is thread-safe because it only uses shared variables:

	int delegate(int) func() {
		shared int a = 1, b = 12;
		return (int i){ return a*i + b; }
	}

So above we have one thread-local delegate and two thread-safe delegates. It also happens that the type system already has a type for thread-safe delegates: "shared int delegate(int)", it's just impossible to create one such.

So the proposal is this:

1. Delegate literals accessing only shared and immutable variables should be typed "shared int delegate(int)", a type which already exists.

2. Type "shared int delegate(int)", denoting a delegate which can be shared among threads, should be implicitly convertible to "int delegate(int)", but not the reverse!

Additionally, taking a delegate from a method on a shared object should return a shared delegate (which can be converted to a non-shared delegate).

I don't see that as really complicated. We already have all the types needed, they just need to be glued together correctly.

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





More information about the dmd-concurrency mailing list