![](/img/trans.png)
[英]how to create a struct and pass to a new thread via pthread_create()
[英]How to pass an array of struct to pthread_create? C
幫助!!!! 如何將args.tab1 轉換為(void *)並將其作為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
不在堆棧上(即您為它分配了 memory 並且它是指向該內存的指針)。
Output:
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);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.