【问题标题】:How to pass an array of struct to pthread_create? C如何将结构数组传递给pthread_create? C
【发布时间】:2020-09-26 00:16:31
【问题描述】:

帮助!!!! 如何将 args.tab1 转换为 (void *) 并将其作为 pthreadargument 传递?谢谢

//结构

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) 
{
...
}

【问题讨论】:

  • 你想传递结构还是只传递tab1?
  • 你好托尼,只是 tab1 但我也很想知道如何传递整个结构

标签: c arrays struct arguments pthreads


【解决方案1】:

没有必要投射。将任何指针转换为void * 时,编译器不会抱怨。做吧

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

【讨论】:

  • 感谢马塞洛的回复!我只是编辑我的问题。我忘了在问题中添加 typedef。我怎样才能只通过 tab1?
  • 好的,我已经相应地修复了响应。
  • 感谢马塞洛,它有效! :) 你能解释一下为什么我们需要添加 & 吗?
  • 只有在传递指向 arg.tab1 的指针时才需要它,即,如果您想更改指针本身的值。如果您只想访问或更改 arg.tab1 指向的整数值,那么您不想使用&。请注意,当您更改代码时,我已在答案中更改了这一点。
【解决方案2】:

关于如何传递结构的演示

#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);
   ...
}

【讨论】:

  • 感谢 Tony 的回复,我更了解如何传递结构。有没有办法只通过tab1?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多