Passing parameters to thread functions

Adam D. Ruppe via Digitalmars-d digitalmars-d at puremagic.com
Sat Aug 15 05:46:20 PDT 2015


In the documentation, it talks about derived threads in one of 
the examples. That's one way to do this:

import core.thread;

// Thread sub class can hold data
// we pass the params through the constructor
class MyThread : Thread {
         uint* var;
        // ref only works one level deep - it stops being ref when 
you assign it somewhere else
        // so we use a pointer instead
         this(uint* var) {
                 this.var = var;
                 super(&run);
         }
         void run() {
                 uint v = *var << 1;
                 *var = v;
         }
}
int main()
{
     uint val = 7;
     auto thread1 = new MyThread(&val).start();
     thread1.join();
     return 0;
}



You can also use a delegate inline instead of a separate function:

import core.thread;
int main()
{
     uint val = 7;
       // the inline defined {} returns a delegate which
       // Thread will accept, and it can access local vars
       // directly
     auto thread1 = new Thread({ val <<= 1; } ).start();
     thread1.join();
     return 0;
}


That delegate is the shortest code but keep in mind that val is 
now shared by the main thread and the child thread and may be 
written to by both of them at once...


Or there's also http://dlang.org/phobos/std_concurrency.html#spawn

the spawn function from std.concurrency, which is meant to give 
you functions for message passing between threads but also lets 
you start one like this:


import core.thread, std.concurrency;

void thread_proc(shared(uint)* var)
{
     uint v = *var << 1;
     *var = v;
}

int main()
{
     shared(uint) var = 7; // has to be shared tho!
     spawn(&thread_proc, &var); // pass args to it here

     thread_joinAll(); // it doesn't return the Thread object 
though... spawn returns a Tid used for send and receive messages, 
so we join differently

     return 0;
}



The big change here is the explicit shared(uint) instead of plain 
uint. core.thread lets you share stuff implicitly (which can get 
weird with two threads writing to it at the same time). 
std.concurrency requires you to be more explicit about it.


More information about the Digitalmars-d mailing list