Sunday, May 23, 2010

Task Parallel Library

Code Snippet
  1. void SeqMatrixMult(int size, double[,] m1, double[,] m2, double[,] result)
  2. {
  3. for (int i = 0; i < size; i++) {
  4. for (int j = 0; j < size; j++) {
  5. result[i, j] = 0;
  6. for (int k = 0; k < size; k++) {
  7. result[i, j] += m1[i, k] * m2[k, j];
  8. }
  9. }
  10. }
  11. }

The previous code heavily consume processor ,although you have 4-quad processor. is there any way to make your 4-quad processor (or your 4 processor) help you? what if u let the iterations divided into 4 portions (each processor processes a portion)

There new class in .net framework called “Parallel” which has static methods called “For”, and “Foreach”

This class is in the TPL “Task Parallel Library”(see the note at the end of the article.)

you just add the follwoing namespace

Code Snippet
  1. using System.Concurrency;
  2. void ParMatrixMult(int size, double[,] m1, double[,] m2, double[,] result)
  3. {
  4. Parallel.For( 0, size, delegate(int i) {
  5. for (int j = 0; j < size; j++) {
  6. result[i, j] = 0;
  7. for (int k = 0; k < size; k++) {
  8. result[i, j] += m1[i, k] * m2[k, j];
  9. }
  10. }
  11. });
  12. }

“Parallel.For” is a static method takes the start and end index of the loop and the third parameter is the value of the index loop  to pass to the processor. But it has some constraints .that the inner loops do not depend on the outer loops.

Meaning that the next iteration does not depend on the current iteration (in other words, does not wait for a value from the prev. iteration - the index loop variable is already passed to the processor(actually, it’s a thread running on the other processor).

For the non-numeric values there is the Parallel. Foreach

End of the story.

Note:

TPL is being created as a collaborative effort by Microsoft® Research, the Microsoft Common Language Runtime (CLR) team, and the Parallel Computing Platform team. TPL is a major component of the Parallel FX library, the next generation of concurrency support for the Microsoft .NET Framework

 

C# fast-food by:
Eng.Waleed abou-zaid
Senior Software Developer
Harf Information Technology
MCSD.Net,MCAD.Net,MCP,A+,N+ certified
walid.abouzaid@gmail.com



0 comments: