linux系统下,c语言pthread多线程编程传参问题

linux系统下,c语言pthread多线程编程传参问题,第1张

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

}

矩阵的计算我忘记了,你运行看看结果对不对

你编译的时候有加多线程连接选项吗? 要加上 -lpthread 或者 -pthread (尽量选后者)

例如 gcc -pthread -o test main.cpp

另外你的线程创建的不对,函数指针不能强转类型(这里也不用转)

pthread_create(&producter_t,NULL,(void*)producter_f,NULL)

pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL)

应该是

pthread_create(&producter_t,NULL,producter_f,NULL)

pthread_create(&consumer_t,NULL,consumer_f,NULL)


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8680046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-19
下一篇 2023-04-19

发表评论

登录后才能评论

评论列表(0条)

保存