在此程序中,主线程不等待子线程,但是当我替换pthread_join的位置并将其放在pthread_create之后的for循环中时,主线程将等待子线程。
我认为如果这样做,我就消除了多线程程序的优势,因为主线程将在创建每个线程之后等待,直到其完成工作,这样程序才能并行运行。
有人可以帮助我提前找到此问题的解决方案吗?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int b[3][2]={{8,9},{7,2},{5,6}};
int c[3][2];
int a_rows=3,a_cols=3,b_rows=3,b_cols=2;
struct dimensions
{
int row;
int col;
};
//method computes C[i][j] in the output C matrix**/
void *matrix_mulCell(void * arg)
{
struct dimensions *d=arg;
int sum=0;
int k;
for(k=0; k<b_rows; ++k)
{
sum+=(a[d->row][k]*b[k][d->col]);
}
c[d->row][d->col]=sum;
/**Exit the thread*/
pthread_exit(NULL);
}
int main()
{
int i,j;
pthread_t threads2[a_rows][b_cols];
struct dimensions *d=(struct dimensions *) malloc(sizeof(struct dimensions));
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
d->row=i;
d->col=j;
/**create thread to compute the value of element c[i][j]**/
if( pthread_create(&threads2[i][j], NULL, matrix_mulCell, d))
{
printf("Can not create a thread\n");
exit(1);
}
}
}
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
/**Make sure the parent waits for all thread to complete**/
pthread_join(threads2[i][j],NULL);
}
}
/**print the result **/
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}
添加@milevyo编辑(为每个线程创建新的结构)并让主线程在程序结尾处等待其他线程之前,在打印矩阵之前而不是在创建子线程之后,这是我的答案
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int b[3][2]={{8,9},{7,2},{5,6}};
int c[3][2];
int a_rows=3,a_cols=3,b_rows=3,b_cols=2;
struct dimensions
{
int row;
int col;
};
//method computes C[i][j] in the output C matrix**/
void *matrix_mulCell(void * arg)
{
struct dimensions *d=arg;
int sum=0;
int k;
for(k=0; k<b_rows; ++k)
{
sum+=(a[d->row][k]*b[k][d->col]);
}
c[d->row][d->col]=sum;
/**Exit the thread*/
free(d);// thread is responsible of freeing it
pthread_exit(NULL);
}
int main(void)
{
int i,j;
pthread_t threads2[a_rows][b_cols];
memset(c,0,sizeof(c));
struct dimensions *d;
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
// allocate for each thread it own struct
// thread it self will free it
d=malloc(sizeof(struct dimensions));
d->row=i;
d->col=j;
/**create thread to compute the value of element c[i][j]**/
if( pthread_create(&threads2[i][j], NULL, matrix_mulCell, d))
{
printf("Can not create a thread\n");
exit(1);
}
}
}
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
/**make main thread wait for child threads**/
pthread_join(threads2[i][j],NULL);
}
}
/**print the result **/
for(i=0; i<a_rows; ++i)
{
for(j=0; j<b_cols; ++j)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句