3个线程使用的都是同一个info
代码 Info_t *info = (Info_t *)malloc(sizeof(Info_t))只创建了一个info
pthread_create(&threads[i],NULL,calMatrix,(void *)info)三个线程使用的是同一个
我把你的代码改了下:
#include <stdio.h>#include <stdlib.h>
#include <pthread.h>
int mtc[3] = { 0 } // result matrix
typedef struct
{
int prank
int *mta
int *mtb
}Info_t
void* calMatrix(void* arg)
{
int i
Info_t *info = (Info_t *)arg
int prank = info->prank
fprintf(stdout,"calMatrix : prank is %d\n",prank)
for(i = 0 i < 3 i++)
mtc[prank] += info->mta[i] * info->mtb[i]
return NULL
}
int main(int argc,char **argv)
{
int i,j,k = 0
int mta[3][3]
int mtb[3] = { 1 }
Info_t *info = (Info_t *)malloc(sizeof(Info_t)*3)
for(i = 0 i < 3 i++)
for(j = 0 j < 3 j++)
mta[i][j] = k++
/* 3 threads */
pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t)*3)
fprintf(stdout,"\n")fflush(stdout)
for(i = 0 i < 3 i++)
{
info[i].prank = i
info[i].mta = mta[i]
info[i].mtb = mtb
pthread_create(&threads[i],NULL,calMatrix,(void *)(&info[i]))
}
for(i = 0 i < 3 i++)
pthread_join(threads[i],NULL)
fprintf(stdout,"\n==== the matrix result ====\n\n")
fflush(stdout)
for(i = 0 i < 3 i++)
{
fprintf(stdout,"mtc[%d] = %d\n",i,mtc[i])
fflush(stdout)
}
return 0
}
矩阵的计算我忘记了,你运行看看结果对不对
·线程创建函数原型:int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void),void *restrict arg)
返回值:若是成功建立线程返回0,否则返回错误的编号。
形式参数:pthread_t *restrict tidp要创建的线程的线程id指针;
const pthread_attr_t *restrict attr创建线程时的线程属性;
void* (start_rtn)(void)返回值是void类型的指针函数;
void *restrict arg start_rtn的形参。 =====这个地方就可以传参数,
注意,这个地方是个指针,要想传多个参数,可以定义一个结构体,把要传的参数包起来,传结构体的地址就ok