[英]How to pass an array of struct to pthread_create? C
Help!!!!帮助!!!! How can I cast args.tab1 to (void *) and pass it as an argument of pthread ?
如何将args.tab1 转换为(void *)并将其作为pthread的参数传递? Thanks
谢谢
//struct //结构
typedef struct args args;
struct args {
int *tab1;
int *tab2;
int *tab3;
int *tab4;
};
//pthread //pthread
args args; //define struct
pthread_t tid;
pthread_create(&tid, NULL, function1, (void *)args.tab1);
pthread_join(tid, NULL);
//function1 //函数1
void *function1(void *input)
{
int *arr = (int*)input;
function2(arr);
}
//function2
void function2(int *arr)
{
...
}
There is no need to cast.没有必要投。 The compiler will not complain when casting any pointer to
void *
.将任何指针转换为
void *
时,编译器不会抱怨。 Just do做就是了
args a;
pthread_create(&tid, NULL, function1, a.tab1);
A demo on how to pass a struct关于如何传递结构的演示
#include <pthread.h>
#include <stdio.h>
struct args {
int *tab1;
int *tab2;
int *tab3;
int *tab4;
};
void *f(void *arg)
{
struct args *o = (struct args *)arg;
printf("%d\n", *(o->tab1));
printf("%d\n", *(o->tab2));
printf("%d\n", *(o->tab3));
printf("%d\n", *(o->tab4));
}
int main()
{
pthread_t thread1;
int n = 100;
struct args o = {
.tab1 = &n,
.tab2 = &n,
.tab3 = &n,
.tab4 = &n
};
pthread_create(&thread1, NULL, f, &o);
pthread_join(thread1, NULL);
}
Alternatively, you could或者,您可以
pthread_create(&thread1, NULL, f, o);
If o
wasn't on stack (ie you allocated memory for it and it's the pointer to that memory).如果
o
不在堆栈上(即您为它分配了 memory 并且它是指向该内存的指针)。
Output: Output:
100
100
100
100
And if you only wish to pass a single pointer from struct args
then如果您只想从
struct args
传递一个指针,那么
void *f(void *arg)
{
int* tab1 = (int *)arg;
printf("%d\n", *tab1);
}
int main()
{
...
pthread_create(&thread1, NULL, f, o.tab1);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.