gpt4 book ai didi

c - 使用 pthread_create() 时将结构作为参数传递

转载 作者:太空狗 更新时间:2023-10-29 16:30:48 25 4
gpt4 key购买 nike

我尝试在使用 pthread_create() 时将结构作为第四个参数传递:

pthread_create(&tid1, NULL, calca, &t); //t is the struct

现在每当我尝试访问结构中的变量时 - t.a、t.b 或 t.c,我总是收到错误 - 请求成员不是结构或 union 。

我可以使用什么替代方法将结构传递到线程中?

最佳答案

您可能正在与 pthread_create 相同的范围内创建结构。一旦退出该范围,该结构将不再有效。

尝试创建一个指向堆上结构的指针并将该结构指针传递给您的线程。不要忘记在某处删除该内存(如果您永远不会再次使用它,则在线程中 - 或者当您不再需要它时)。

此外,正如 cyberconte 所提到的,如果您要从不同的线程访问该数据,则需要使用互斥锁或关键部分来锁定对它的访问。

编辑 2009 年 5 月 14 日 @ 12:19 PM EST:另外,正如其他人提到的,您必须将参数转换为正确的类型。

如果您要传递一个全局结构变量(您似乎坚持这样做),您的线程函数将必须转换为以下类型:

void my_thread_func(void* arg){
my_struct foo = *((my_struct*)(arg)); /* Cast the void* to our struct type */
/* Access foo.a, foo.b, foo.c, etc. here */
}

或者,如果您将指针传递给您的结构:

void my_thread_func(void* arg){
my_struct* foo = (my_struct*)arg; /* Cast the void* to our struct type */
/* Access foo->a, foo->b, foo->c, etc. here */
}

关于c - 使用 pthread_create() 时将结构作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/863952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com