求救!!!如何将args.tab1强制转换为(void *)并将其作为pthread的argument传递?谢谢
// struct
typedef struct args args;
struct args {
int *tab1;
int *tab2;
int *tab3;
int *tab4;
};
// pthread
args args; //define struct
pthread_t tid;
pthread_create(&tid, NULL, function1, (void *)args.tab1);
pthread_join(tid, NULL);
//功能1
void *function1(void *input)
{
int *arr = (int*)input;
function2(arr);
}
//function2
void function2(int *arr)
{
...
}
无需铸造。将任何指针投射到void *
时,编译器都不会抱怨。刚做
args a;
pthread_create(&tid, NULL, function1, a.tab1);
有关如何传递结构的演示
#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);
}
或者,您可以
pthread_create(&thread1, NULL, f, o);
如果o
不在堆栈上(即,您为其分配了内存,它是指向该内存的指针)。
输出:
100
100
100
100
并且,如果您只希望从struct args
传递单个指针,则
void *f(void *arg)
{
int* tab1 = (int *)arg;
printf("%d\n", *tab1);
}
int main()
{
...
pthread_create(&thread1, NULL, f, o.tab1);
...
}