View mode: basic / threaded / horizontal-split · Log in · Help
April 26, 2011
How to spawn variable-length functions?
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. :]
April 26, 2011
Re: How to spawn variable-length functions?
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/
Top | Discussion index | About this forum | D home