使用struct(pthread)将多个参数传递给线程
我正在学习使用pthread为加法器程序编程,在参考了一些代码后,仍然不知道如何使用struct将多个参数传递到线程中,下面是我的错误程序:使用struct(pthread)将多个参数传递给线程,struct,pthreads,Struct,Pthreads,我正在学习使用pthread为加法器程序编程,在参考了一些代码后,仍然不知道如何使用struct将多个参数传递到线程中,下面是我的错误程序: #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> typedef struct s_addition { int num1; int num2; int sum; } addit
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
typedef struct s_addition {
int num1;
int num2;
int sum;
} addition;
void *thread_add_function (void *ad)
{
printf ("ad.num1:%d, ad.num2:%d\n",ad.num1, ad.num2);
ad.sum = ad.num1 + ad.num2;
pthread_exit(0);
}
int main()
{
int N = 5;
int a[N], b[N], c[N];
srand (time(NULL));
// fill them with random numbers
for ( int j = 0; j < N; j++ ) {
a[j] = rand() % 392;
b[j] = rand() % 321;
}
addition ad1;
pthread_t thread[N];
for (int i = 0; i < N; i++) {
ad1.num1 = a[i];
ad1.num2 = b[i];
printf ("ad1.num1:%d, ad1.num2:%d\n",ad1.num1, ad1.num2);
pthread_create (&thread[i], NULL, thread_add_function, &ad1);
pthread_join(thread[i], NULL);
c[i] = ad.sum;
}
printf( "This is the result of using pthread.\n");
for ( int i = 0; i < N; i++) {
printf( "%d + %d = %d\n", a[i], b[i], c[i]);
}
}
#包括
#包括
#包括
#包括
类型定义结构s_加法{
int num1;
int num2;
整数和;
}添加;
void*线程添加函数(void*ad)
{
printf(“ad.num1:%d,ad.num2:%d\n”,ad.num1,ad.num2);
ad.sum=ad.num1+ad.num2;
pthread_退出(0);
}
int main()
{
int N=5;
int a[N],b[N],c[N];
srand(时间(空));
//用随机数填充它们
对于(int j=0;j
但在编译时,我遇到了以下错误:
vecadd_parallel.c:15:39:错误:成员引用基类型“void*”不是
结构或结合
printf(“ad.num1:%d,ad.num2:%d\n”,ad.num1,ad.num2)
我试过了,但还是找不到线索,我到底做错了什么?似乎您在尝试访问无效数据类型的成员时遇到了问题 您需要添加一行,将参数转换为
thread\u add\u function
的正确数据类型,类似于addition*add=(addition*)ad
,然后在函数中使用此变量(注意,您还必须将r
更改为->
,因为它是指针)
您还应该只将数据传递给
malloc()
'd的线程,因为堆栈分配的数据可能不是永久的。对于当前的实现来说应该没问题,但是以后的更改很容易导致奇怪的、不可预测的行为。谢谢,我终于找到了问题所在!但是我不完全理解你的第二个建议,我想知道我怎样才能找到一个线程,你能给我指一些参考资料吗?这只是一个小小的建议。您不应该将数据在堆栈上的位置传递给pthread_create
的最后一个参数,因为如果该数据在函数中,并且返回,则该数据可以重用或具有未定义的值。您不应该对当前代码有任何问题,因为所有线程都在主函数返回之前完成,并且程序在返回时退出。