Functional Muti-threading

janderson askme at me.com
Sun Jan 21 19:17:06 PST 2007


Case in point:

To take an example from Kevin Bealer,

int sum(int[] x)
{
     int rv = 0;
     foreach(int y; x) {
         rv += y;
     }
     return rv;
}

int sum_4(int[] x)
{
     alias Future!(int) FInt;
     int part = x.length/4;

     // Each of these queues a work item to be done either on some
     // other thread, or by the main thread here.

     FInt x1 = new FInt({ return sum(x[0..part]); });
     FInt x2 = new FInt({ return sum[part..part*2]); });
     FInt x3 = new FInt({ return sum[part*2..part*3]); });
     FInt x4 = new FInt({ return sum[part*3..$]; });

     // The addition below waits for each results to complete
     // before adding it to the total.

     return x1.value + x2.value + x3.value + x4.value;
}


Could be written like:
int sum(int[] x)
{
     int rv = 0;
     threadable(4) foreach(int y; x) {
         rv += y;
     }
     return rv;
}

Or even better
threadable int sum(int[] x)
{
     int rv = 0;
     threadable(4) foreach(int y; x) {
         rv += y;
     }
     return rv;
}

Now sum can be spliced in with other CPU independent operations. ir

int foo(int[] a, int b[])
{
   return sum(a) + sum(b); //Both run in parallel
}

Better still, we can turn it off with a simple compiler flag to get 
single threaded performance.

Obviously we have Futurism library now however I make this suggestion 
for D2.0.  I'm sure there are a few problems in the syntax that i 
presented that will need to be worked though.  Or maybe the edge cases 
are just too difficult to make this feasible?

Oh, and for anyone who still hasn't see Herb Sutter's video:

http://video.google.com/videoplay?docid=7625918717318948700&q=sutter

It explains why it is so important to figure out how multi-threading is 
going to be handled in D.



More information about the Digitalmars-d mailing list