www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to spawn variable-length functions?

reply Andrej Mitrovic <none none.none> writes:
import std.stdio;
import std.concurrency;

void print(int[] a...)
{
    foreach(b; a)
        writeln(b);
}

void main()
{
    int value;
    spawn(&writeln, value);
    spawn(&print, value);
}

Neither of these calls will work. I want to continuously print some values but
without blocking the thread that issues the call to print, and without using
locks. Since it's a print function I need it to take a variable number of
arguments.

How do I go around doing this? Perhaps I could use some kind of global
Variant[] that is filled with values, and a foreground thread pops each value
as it comes in and prints it?

Or maybe I should use send()?

I'm looking for something fast which doesn't slow down or pause the work thread.

Multithreading is hard business. :]
Apr 26 2011
parent Robert Clipsham <robert octarineparrot.com> writes:
On 26/04/2011 19:48, Andrej Mitrovic wrote:
 import std.stdio;
 import std.concurrency;

 void print(int[] a...)
 {
      foreach(b; a)
          writeln(b);
 }

 void main()
 {
      int value;
      spawn(&writeln, value);
      spawn(&print, value);
 }

 Neither of these calls will work. I want to continuously print some values but
without blocking the thread that issues the call to print, and without using
locks. Since it's a print function I need it to take a variable number of
arguments.

 How do I go around doing this? Perhaps I could use some kind of global
Variant[] that is filled with values, and a foreground thread pops each value
as it comes in and prints it?

 Or maybe I should use send()?

 I'm looking for something fast which doesn't slow down or pause the work
thread.

 Multithreading is hard business. :]
Try this: ---- import std.concurrency; import std.stdio; void printer() { try { while(true) { writeln(receiveOnly!int()); } } catch(OwnerTerminated) { } } void main() { auto tid = spawnLinked(&printer); send(tid, 2); send(tid, 3); send(tid, 4); } ---- -- Robert http://octarineparrot.com/
Apr 26 2011