ºìÁªLinuxÃÅ»§
Linux°ïÖú

pthread±à³ÌÓë¶àºËµÄÎÊÌâ

·¢²¼Ê±¼ä:2008-07-28 21:45:58À´Ô´:ºìÁª×÷Õß:linuxdog
Á½¸ö´ó¾ØÕó(1000*1000)Ïà³ËµÄÔËËãÎÊÌ⣬ÓÃÁ½¸öỊ̈߳¨Ò»¸ö¼ÆËãÇ°N/2µÄÊý¾Ý£¬Ò»¸ö¼ÆËãºóN/2µÄÊý¾Ý,±£Ö¤Ã»ÓÐÖصþ)À´¼ÆËã¸úʹÓÃÒ»¸öÏ̼߳ÆËã(´®ÐÐ)µÄʱ¼ä¾¹È»ÊDz¶àµÄ¡£

cpuÊÇË«ºËµÄ....
------------------------------

Àí½âÖÐ,2¸öÏ̵߳ÄÔËËãʱ¼äÓ¦¸Ã²î²»¶àÊÇ´®ÐеÄÒ»°ë°¡.ÒòΪÁ½¸öÏ̷ֱ߳𱻵÷µ½2¸öcpuºËÖзֱðÈ¥ÔËÐÐÁË°¡.ÄÚºËÖÐʹÓõÄÊÇNPTLÏ߳̿⡣

½á¹ûÔõô»áÕâÑù?

(³ÌÐòÉè¼ÆÓ¦¸ÃûÓÐÎÊÌâ.)
---------------------------------------------------
#include
#include
#include
#include

const int MATRIX_SIZE=1000; //¾ØÕó´óС
typedef int DataType;
DataType **matrixA,**matrixB,**result;

void InitMatrix(DataType ***matrix) //·ÖÅä¶þλÊý×éµÄ¿Õ¼ä²¢³õʼ»¯
{
*matrix=(DataType**)malloc(sizeof(DataType*)*MATRIX_SIZE);
int i,j;
for(i=0; i (*matrix)[i]=(DataType*)malloc(sizeof(DataType)*MATRIX_SIZE);

srand((unsigned)time(NULL));
for(i=0; i for(j=0; j (*matrix)[i][j]=rand()%100;
}
void FreeMatrix(DataType **matrix)
{
int i;
for(i=0; i free(matrix[i]);
free(matrix);
}

//´®ÐÐ
void Calculate()
{
int i,j,k;
double start, finish;
start=(double)clock();
for(i=0; i for(j=0; j {
result[i][j]=0;
for(k=0; k result[i][j]+=matrixA[i][k]*matrixB[k][j];
}
finish=(double)clock();

//printf("total time=%.4lf\n", (finish-start)/CLOCKS_PER_SEC);
}


//²¢ÐÐ
const int NumThread=2; //Ï̸߳öÊý

void* threadhandle(void *dum)
{
int i,j,k;
int start=*((int*)dum);
int stop=start+500;
for(i=start; i for(j=0;j {
result[i][j]=0;
for(k=0; k result[i][j]+=matrixA[i][k]*matrixB[k][j];
}
}

//²¢ÐмÆËã:´´½¨2¸öÏß³Ì
void Calculate_Parallel()
{
int i;
pthread_t pid[NumThread];
double start, finish;
start=(double)clock();
for(i=0; i pthread_create(&(pid[i]), NULL, threadhandle,&i);
finish=(double)clock();
pthread_join(pid[i], NULL);
printf("total time=%.4lf\n", (finish-start)/CLOCKS_PER_SEC);
}


int main()
{

InitMatrix(&matrixA);
InitMatrix(&matrixB);
InitMatrix(&result);

Calculate();
Calculate_Parallel();

FreeMatrix(matrixA);
FreeMatrix(matrixB);
FreeMatrix(result);
}
ÎÄÕÂÆÀÂÛ

¹²ÓÐ 1 ÌõÆÀÂÛ

  1. faniyou ÓÚ 2008-07-29 15:18:42·¢±í:

    ʹÓà pthread_join(pid, NULL); ½«µ¼ÖÂÏ߳̽áÊøÇ°ÎÞ·¨·µ»Ø
    ËùÒÔ³ÌÐòµÄ×îÖÕ½á¹ûÊÇ˳ÐòÖ´ÐУ¬Ã»ÓÐÓõ½¶àÏ̲߳¢Ðд¦ÀíµÄÓÅÊÆ£¬ËùÒÔʱ¼äÒ»Ñù¡£