如何将结构数组传递给pthread_create? C

时间:2020-06-06 21:27:56

标签: c arrays struct arguments pthreads

帮助!!! 如何将 args.tab1 强制转换为(void *),并将其作为 pthread 自变量传递?谢谢

// 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);

// function1

void *function1(void *input)
{
    int *arr = (int*)input;
    function2(arr);
}

//function2
void function2(int *arr) 
{
...
}

2 个答案:

答案 0 :(得分:0)

无需投射。强制转换任何指向void *的指针时,编译器不会抱怨。随便

    args a;
    pthread_create(&tid, NULL, function1, a.tab1);

答案 1 :(得分:0)

有关如何传递结构的演示

#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);
   ...
}
相关问题