2011年10月15日 星期六

C 矩陣相乘-使用thread(轉貼)

#include <windows.h>
#include <stdio.h>
#define M 3
#define K 2
#define N 3

// structure for passsing data to therads
struct v
{
  int i; // row
  int j; // column     
};
     
int A[M][K] = { {1,4},{2,5},{3,6} };
int B[K][N] = { {8,7,6},{5,4,3} };
int C[M][N];
int i,j;
DWORD WINAPI multiplyThread(LPVOID Param )
{
        // Create structure and assign data from param to it.
        struct v threadVal = *(struct v*)Param;

        int a = threadVal.i;
        int b = threadVal.j;
      
        // cout << a << ' ' << b << endl;
        //Perform the matrix multiplication
        C[a][b]=0;
        for(i =0;i < K; i++)
        C[a][b]+=A[a][i]*B[i][b];
      
        return 0;
}

int main()
{
   DWORD ThreadId;
   HANDLE ThreadHandle;
 
   // printf array A
   printf("Array A is\n");
   for( i= 0; i < M; i++ )
   {
     for( j = 0; j < K; j++ )
        printf("%d ",A[i][j]);
   
     printf("\n");
   }
 
   printf("\n\n");
 
   // printf array B
   printf("Array B is\n");
   for(i= 0; i < K; i++ )
   {
     for(  j = 0; j < N; j++ )
        printf("%d ",B[i][j]);
   
     printf("\n");
   } 
 
   // create M * N worker threads
   for( i= 0; i < M; i++ )
   {
     for(j = 0; j < N; j++ )
     {
       struct v *data = (struct v *) malloc(sizeof(struct v) ); // allocate memory
       data ->i = i;
       data ->j = j;
      // Create Thread to calculate value of matrix at row column
       ThreadHandle = CreateThread(
         NULL, // default security attributes
         0, // default stack size
         multiplyThread, // thread function
         data, // parameter to thread function
         0, // default creation flags
         &ThreadId); // returns the thread identifier
    
      /*
       if ( ThreadHandle != NULL )
       {
         // now wiat for the thread to finish
         WaitForSingleObject(ThreadHandle,INFINITE);
      
         // close the thread handle
         CloseHandle(ThreadHandle);
       }
      
       */      
     }
     printf("\n");
   }
 
   printf("Array A * B is\n");
   for( i= 0; i < M; i++ )
   {
     for(  j = 0; j < N; j++ )
        printf("%d ",C[i][j]);
   
     printf("\n");
   }
 
   printf("\n");
       
   system( "pause" );
   return 0;
}

沒有留言:

張貼留言