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

标签 c multithreading struct pthreads

我尝试在使用 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/

相关文章:

python - 多线程访问python字典

c - 错误: dereferencing pointer to incomplete type -> passing structure to module

ios - 扩展结构不是 Swift 的成员

c++ - 输出无序映射中的结构变量

C : How to make the size of an array dynamic?

带有 int 指针的转换代码

c - 查找 3 位数字的所有可用组合

c - C 中的 *.r 文件是什么?

.net - 异步和 .NET 事件?

c# - WP7(C#)的简单LOCK和ThreadPoolQuestion