Simplest multithreading example

Michael Coulombe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 31 21:02:22 PDT 2017


On Friday, 1 September 2017 at 01:59:07 UTC, Brian wrote:
> Hello, I am trying to get the most trivial example of 
> multithreading working, but can't seem to figure it out.
> I want to split a task across threads, and wait for all those 
> tasks to finish before moving to the next line of code.
>
> The following 2 attempts have failed :
>
> -----------------------------------------------------
> Trial 1 :
> -----------------------------------------------------
>
> auto I = std.range.iota(0,500);
> int [] X; // output
> foreach (i; parallel(I) )
>     X ~= i;
> core.thread.thread_joinAll(); // Apparently no applicable here ?
> writeln(X); // some random subset of indices
>
> ------------------------------------------------
> Trial 2 : (closer to Java)
> ------------------------------------------------
> class DerivedThread : Thread
> {
>     int [] X;
>     int i;
>     this(int [] X, int i){
>         this.X = X;
> 	this.i = i;
>         super(&run);
>     }
>
>     private:
>         void run(){
>             X ~= i;
>         }
> }
>
> void main(){
> 	auto I = std.range.iota(0,500);
> 	int [] X; // output
> 	Thread [] threads;
> 	foreach (i; I )
> 		threads ~= new DerivedThread( X,i);
> 	foreach( thread; threads)
> 		thread.start();
> 	foreach( thread; threads)
> 		thread.join(); // does not seem to do anything
> 	core.thread.thread_joinAll(); // also not doing anything
>
> 	writeln(X); // X contains nothing at all
> }
>
> How can I get the program to wait until all threads have 
> finished before moving to the next line of code ?
>
> Thank you !

Just like a sequential loop, when you do "foreach (i; parallel(I) 
) { ... }", execution will not continue past the foreach loop 
until all the tasks associated with each element of I have 
finished.

Your particular example of "X ~= i" in the body of the loop is 
not thread-safe, so if that is the code you really intend to run, 
you should protect X with a Mutex or something comparable.


More information about the Digitalmars-d-learn mailing list