您好,欢迎访问三七文档
当前位置:首页 > 临时分类 > 操作系统概念LAB4—矩阵相乘—实验报告
LAB4实验报告实验目的:1.矩阵相乘实验内容:给定两个矩阵A和B,其中A是具有M行、K列的矩阵,B为K行、N列矩阵,A和B的矩阵积为C,C为M行,N列。矩阵C中第i行、第j列的元素Ci,j就是矩阵A第i行每个元素和矩阵B第j列每个元素乘积的和。本实验的目的是通过对矩阵乘法是多线程实现,让学生加深对线程的理解与调用。实验步骤:在Linux操作系统上,利用Linux处理多线程的优点,编写程序用多线程实现矩阵乘法。实现A、B两个矩阵的乘法,并输出计算结果。实验代码如下:#includestdio.h#includetime.h#includepthread.h#includestdlib.h#includeunistd.h#includememory.h#defineRANGE100#defineM2#defineK2#defineN2voidgene_matrix();voidread_matrix();intmatrixA[M][N]={{1,1},{2,2}};intmatrixB[N][M]={{4,14},{5,25}};intarr[M][M][N];intres[M][N]={0};void*func(void*arg);main(){clock_tstart=clock();inti,j,k,cnt,cnt2;pthread_ttids[N];for(i=0;iN;i++){if(pthread_create(&tids[i],NULL,func,(void*)&i)){perror(pthread_create);exit(1);}pthread_join(tids[i],NULL);}for(i=0;iN;i++)pthread_join(tids[i],NULL);for(i=0;iM;i++)for(j=0;jM;j++){for(k=0;kN;k++)res[i][j]+=arr[i][j][k];printf(res[%d][%d]=%d\n,i,j,res[i][j]);}clock_tfinish=clock();printf(n,(long)(finish-start)/1E6);}void*func(void*arg){intk=*(int*)arg;inti,j;printf(Enterfunc\n);for(i=0;iM;i++){for(j=0;jN;j++){arr[i][j][k]=matrixA[i][k]*matrixB[k][j];printf(func=%d\n,arr[i][j][k]);}}pthread_exit(NULL);}voidgene_matrix(){FILE*file1,*file2;if((file1=fopen(/home/timelong/Desktop/matrixA,wt))==NULL){perror(fopen);exit(1);}if((file2=fopen(/home/timelong/Desktop/matrixB,wt))==NULL){perror(fopen);exit(1);}inti,j;srand((unsigned)time(NULL));for(i=0;iM;i++){for(j=0;jN;j++)fprintf(file1,%-8d,rand()%RANGE);fprintf(file1,\n);}fclose(file1);for(i=0;iN;i++){for(j=0;jM;j++)fprintf(file2,%-8d,rand()%RANGE);fprintf(file2,\n);}fclose(file2);}voidread_matrix(){FILE*file1,*file2;if((file1=fopen(/home/timelong/Desktop/matrixA,rt))==NULL){perror(fopen);exit(1);}if((file2=fopen(/home/timelong/Desktop/matrixB,rt))==NULL){perror(fopen);exit(1);}inti,j;for(i=0;iM;i++)for(j=0;jN;j++){fscanf(file1,%d,&matrixA[i][j]);printf(matrixA[%d][%d]=%d\n,matrixA[i][j]);}fclose(file1);for(i=0;iN;i++)for(j=0;jM;j++){fscanf(file2,%d,&matrixB[i][j]);printf(matrixB[%d][%d]=%d\n,matrixB[i][j]);}fclose(file2);}编译代码:gcc-O2-Wall-omyMartixmyMartix.c-pthread运行程序:
本文标题:操作系统概念LAB4—矩阵相乘—实验报告
链接地址:https://www.777doc.com/doc-2381302 .html