Looking for command for synchronization of threads

FG home at fgda.pl
Thu Jan 31 04:00:37 PST 2013


On 2013-01-31 03:29, Sparsh Mittal wrote:
> Thanks. I wrote this:  [...]
> It compiles but barrier does not get released. Can you please point out the
> fault. Pardon my mistake. I searched whole web, there are almost no examples of
> it online.

Barrier doesn't release because you've only called wait() from one thread, while 
initializing the Barrier to use two threads. The following code works for me. 
Notice that the Barrier and wait() are used in 3 threads. But better have this 
verified by someone who had done more threading in D. :)

     #!/usr/bin/env rdmd

     import std.stdio;
     import std.concurrency;
     import std.algorithm;
     import core.sync.barrier;
     import core.thread;

     __gshared Barrier barrier = null;

     void sorter(Tid owner, shared(int)[] sliceToSort, int mynumber)
     {
         writefln("Came inside  %s", mynumber);
         sort(sliceToSort);
         writefln("Going out of %s", mynumber);
         barrier.wait();
     }

     void main()
     {
         shared numbers = [ 6, 5, 4, 3, 2, 1 ];
         barrier = new Barrier(3);
         spawn(&sorter, thisTid, numbers[0 .. $ / 2], 0);
         spawn(&sorter, thisTid, numbers[$ / 2 .. $], 1);

         writefln("Waiting for barrier in main");
         barrier.wait();
         writefln("All done");

         writeln(numbers);
     }



More information about the Digitalmars-d-learn mailing list