gpt4 book ai didi

c - 如何使用 pthreads 在 c 中返回数组?

转载 作者:行者123 更新时间:2023-11-30 16:43:49 24 4
gpt4 key购买 nike

我尝试编写一个程序,线程通过向线程传递随机 vector 来返回数字数组,并且线程返回该 vector 的 2 倍。该程序运行良好,但我没有得到预期的输出。代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble()
{

int *sum[10];
for(i=0;i<5;i++)
{
sum[i]= first[i] + first[i];
}

pthread_exit(sum[i]);
}

int main()
{

double total = omp_get_wtime();

printf("This is using PThread\n");

pthread_t tid1;
pthread_create(&tid1, NULL, myThreaddouble, NULL);
printf("Double of the vector:- \n");
for ( i = 0 ; i < 5 ; i++ )
{
printf(" %d\n",(int) sum[i]);
}
pthread_join(tid1, sum[i]);

total = omp_get_wtime() - total;
printf("%lf is time to add\n",total);
printf("\n");

return 0;

}

输出如下:

This is using PThread
Double of the vector:-
0
0
0
0
0
0.000188 is time to add

这不是预期的输出,所以有人可以告诉我这段代码中有什么错误以及如何使用 pthread 返回数组。在 i 中应该能够对所有返回值求和。

我使用了gcc q.c -lpthread -lrt -fopenmp命令来编译这个程序。

提前谢谢您!

最佳答案

给你。我冒昧地注释掉了时间计算部分。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <omp.h>
void *myThreaddouble();

int i,sum[10],first[10]={10,20,30,40,50};

void *myThreaddouble(void *a)
{

//int *sum[10];
for(i=0;i<5;i++)
{
sum[i]= first[i] + first[i];
}

//pthread_exit(sum[i]);
pthread_exit(NULL);
}

int main()
{

// double total = omp_get_wtime();

printf("This is using PThread\n");

pthread_t tid1;
pthread_create(&tid1, NULL, myThreaddouble, NULL);
printf("Double of the vector:- \n");

//pthread_join(tid1, sum[i]);
pthread_join(tid1, NULL);

for ( i = 0 ; i < 5 ; i++ )
{
printf(" %d\n",(int) sum[i]);
}
// pthread_join(tid1, sum[i]);

//total = omp_get_wtime() - total;
//printf("%lf is time to add\n",total);
printf("\n");

return 0;

}

关于c - 如何使用 pthreads 在 c 中返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44940127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com