【问题标题】:Passing 2 structures as parameters to pthread in C将2个结构作为参数传递给C中的pthread
【发布时间】:2013-03-29 12:43:41
【问题描述】:

我可以将两个结构作为参数传递给 C 程序中的 pthread。我需要做这样的事情:

void *funtion1(void *pass_arg, void *pass_arg1)
{
    struct thread_arg *con = pass_arg;
    struct thread_arg1 *con = pass_arg1;
    //necessary code
}
int main()
{
pthread_t threaad;
//necessary code
while(1)
{
    th1 = pthread_create(&threaad, NULL, function1, (void *)&pass_arg, (void*)&pass_arg);
//necessary codes
}
pthread_exit(NULL);
return 1;
}

我的意思是有什么方法可以在使用 pthread 时将两个结构传递给同一个函数?操作平台:Linux。

【问题讨论】:

  • 在第一个结构中埋入指向第二个结构的指针?
  • 如何在第一个结构中隐藏指向第二个结构的指针?
  • 您是如何定义struct thread_arg 中的current 字段的?再添加一个 (struct thread_arg1 *p1;) 是否超出了可能性范围?

标签: c linux struct pthreads arguments


【解决方案1】:

定义一个包含两个原始类型作为成员的新结构类型。称它为有意义的东西,例如thread_args

【讨论】:

  • 你的意思是通过嵌套我需要作为参数传递的两个结构来创建一个结构?
【解决方案2】:

不是直接的,因为 libpthread 中的函数只接受一个用户数据参数。但这应该足够了,不是吗?

struct user_struct {
    void *p1, *p2;
} arg = { &arg1, &arg2 };

pthread_create(&tid, NULL, threadfunc, &arg);

另外,不要将指针指向void *,这是多余的、危险的并且会降低可读性。

【讨论】:

  • 我的指针相当薄弱。你能告诉我如何使用指针将结构嵌套在另一个结构中以及如何调用它们吗?
  • @HarikrishnanT 我刚刚在示例中展示了这一点。你读了吗?
【解决方案3】:

我通过将两个结构嵌套到一个结构中解决了这个问题,如下所示:

struct s1
{
    //variables
};

struct s2
{
    //variables
}

struct s3
{
    struct s1 ss1;
    struct s2 ss2;
}
void *funtion1(void *pass_arg)
{
    struct s3 *con = pass_arg;
    //necessary code
}
int main()
{
    //code
    th1 = pthread_create(&thread, NULL, function1, (void *)&pass_arg);
}

【讨论】:

  • 这看起来非常接近 Oli 提出的解决方案。 SO 的传统是您 (1) 承认这一点,(2) 支持他的答案,(3) 接受该答案。
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 2011-02-09
  • 2021-12-10
  • 1970-01-01
相关资源
最近更新 更多