Can/should spawn work with functions that return?

Andrej Mitrovic none at none.none
Fri Jan 21 14:12:18 PST 2011


import std.stdio;
import std.concurrency;

void foo(int var)
{
}

bool bar(int var)
{
    return true;
}

void barWrapper(int var)
{
    bar(var);
}

void main()
{
    spawn(&foo, 1);
    spawn(&barWrapper, 1);
    spawn(&bar, 1);
}

Errors:
testSpawn.d(24): Error: template std.concurrency.spawn(T...) does not match any function template declaration
testSpawn.d(24): Error: template std.concurrency.spawn(T...) cannot deduce template function from argument types !()(bool function(int var),int)

Of course, when my foreground thread spawns a background thread it doesn't wait for it to finish, so assigning a return value doesn't make much sense. I can see how that can be an error (in any case that error message above is not very informative).

But what if I want to spawn a thread with an existing function 'bar' that has side-effects, but I'm not interested in its return value even though it has one? 

Right now I'm forced to either:
a) remove any returns from 'bar' and change it to a void function, which can be really complicated if other functions already depend on its return value, or
b) write a new void function that can be called with spawn(), which internally calls 'bar' but discards it's value (so basically it's a wrapper). This is what I've done in the example code.

So, is spawning threads on functions that return banned by design? I couldn't read about this anywhere on the D site or TDPL.


More information about the Digitalmars-d-learn mailing list