New to D - playing with Thread and false Sharing

tony288 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Aug 20 08:31:11 PDT 2015


Hi,

I have been playing for a short time with D. I wanted to play 
with Thread, which I believe is lower level than concurrency and 
parallelism library (might be wrong here ?) .

I was also learning and reading about false sharing - multiple 
thread => same cacheline. And I decided to play with both to 1 
understand more D and see the results of false sharing.

So I wrong some code. But it seems the time to process a shared 
struct & shared long is always the same. Regardless of adding 
paddings.

My thoughts is that as I'm new to D. That it can only be my fault 
and not doing things correctly. I doubt the compiler etc.. adds 
etc padding?

If you have any code to show it, it would be really great.

But this is what I have done : I found this article
http://mechanical-sympathy.blogspot.co.uk/2011/08/false-sharing-java-7.html
and tried to emulate this. In java I do get the same result as 
them and can understand the code. But curious in D i get 
completely different results.

import std.stdio;
import core.time;
import core.thread;

void main() {
		writeln(PaddingStruct.sizeof);
		MonoTime before =  MonoTime.currTime;
	  	runTest();
		MonoTime after = MonoTime.currTime;
		Duration timeElapsed = after - before;
		writeln("Duration is " , timeElapsed)	;

}	


     private static void runTest()
     {
         Thread[] threads = new Thread[4];

         for (int i = 0; i < threads.length; i++)
		 	threads[i] = new FalseSharing(i);//putting a new thread in 
the array
  		foreach(Thread t ; threads){//starts all threads
             t.start();
             }
  		foreach(Thread t; threads){
  			t.join();
  		}

     }

	class FalseSharing : Thread
	{
		private static PaddingStruct[] longs = new PaddingStruct[4];
	    private const int threadIndex;
	    this(const int index)
	    {
	    	threadIndex = index;
	    	PaddingStruct a;
	    	longs[threadIndex] = a;
	        super(&run);
	    }
	    void run()
	    {
	        long i = 500L * 1000L * 1000L;
	        writeln(" threadindex is -> " , threadIndex);
	        writeln(" i is -> " , i);
	        while (0 != --i){longs[threadIndex].value = i;}
	        writeln("threaded ",threadIndex," ended so a=1 -> is it? 
", longs[threadIndex].value);
	    }
	}
  	struct PaddingStruct
	{
		static shared long value = 0L; //shared across multiple thread
		//long p1,p2,p3,p4,p1a;//padding.
     }




More information about the Digitalmars-d-learn mailing list