www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - allow spawn to use delegates

int x;
spawn(() { x = 3; });


This should work, spawn can pass arguments so it can just 
silently package up this and any other args in a tuple and manage 
everything.

I realize there are issues with thread local storage but maybe 
something can be done about this. Obviously local lambdas are 
meant to access the local context and so, while it is potentially 
dangerous, it is probably intended by the user.

One could simply warn or error if any access to "this" is made to 
anything not __gshared.

It's just a pain to have to pass the context info manually.


If one just creates the following template, which is just the 
original spawn template with the function check removed, one has

Tid spawnD(F, T...)(F fn, T args)									
{
     return spawn(fn, args);
}

which allows delegates to be used, sorta. It stops the error for 
some reason but of course any access to the outside context fails.

The following works:

Tid spawnShared(F, T...)(F fn, T args)									
{
     static void wrap(F f, T args)
	{
		f(args);
	}
     return spawn(&wrap, cast(shared)fn, args);
}

as does

spawn(cast(shared)() {									
});

although spawnShared seems to have the ability to correctly fix 
up the delegate to access it's frame.



A better solution would be for the compiler to autofill all 
externally accessed variables and pass them by automatically 
under the hood.
Apr 25 2019