ski*_*ath 17 c multithreading struct pthreads
我尝试将结构作为第4个参数传递,同时使用pthread_create()
类似这样的东西:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
Run Code Online (Sandbox Code Playgroud)
现在每当我尝试访问结构中的变量-ta,tb或tc时,我都会收到错误 - 请求成员不是结构或联合.
我可以使用什么替代方法将结构传递给线程?
Lyn*_*son 24
您可能在与pthread_create相同的范围内创建结构.退出该范围后,此结构将不再有效.
尝试在堆上创建指向结构的指针,并将该结构指针传递给您的线程.不要忘记在某个地方删除那个内存(如果你再也不会使用它,那么就在线程中 - 或者当你不再需要它时).
此外,正如网络控制所提到的,如果您要从不同的线程访问该数据,则需要使用互斥锁或关键部分锁定对它的访问.
编辑2009年5月14日美国东部时间下午12:19:另外,正如其他人提到的那样,你必须将参数转换为正确的类型.
如果您传递的是一个全局结构的变量(您似乎坚持这样),您的线程函数将必须转换为类型:
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 */
}
Run Code Online (Sandbox Code Playgroud)
或者,如果要传递指向结构的指针:
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 */
}
Run Code Online (Sandbox Code Playgroud)