如何将结构数组传递给 pthread_create? C
How to pass an array of struct to pthread_create? C
求助!!!
我如何将 args.tab1 转换为 (void *) 并将其作为 argument 传递 pthread?谢谢
//结构
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);
...
}
求助!!! 我如何将 args.tab1 转换为 (void *) 并将其作为 argument 传递 pthread?谢谢
//结构
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);
...
}