使用 pthread_create() 时将结构作为参数传递
-
21-08-2019 - |
题
我尝试在使用时传递一个结构作为第四个参数 pthread_create()
像这样的东西:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
现在,每当我尝试访问结构中的变量 - t.a、t.b 或 t.c 时,我都会收到错误 - 请求非结构或联合中的成员。
我可以使用什么替代方法将结构传递到线程中?
解决方案
您很可能创造在同一范围内的pthread_create的结构。一旦该范围退出这种结构将不再有效。
尝试创建一个指针到堆上的结构和该结构的指针传递到您的线程。不要忘了删除记忆的地方(在线程,如果你将永远不会再次使用它 - 或者当你不再需要它)。
此外,如cyberconte提到的,如果你将要访问来自不同线程的数据,则需要锁定访问它与互斥或临界区。
修改2009年5月14日@ 12:19 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 */
}
其他提示
如果你是你的线程函数里,你传递参数是一个void *。你需要将它转换为一个结构,然后才能使用它是这样。
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 */
}
创建信号量
创建另一个由指向您的结构的指针和信号量句柄组成的结构
将指向这个新结构的指针传递给 pthread_create
在父线程中,即调用 pthread_create,等待信号量
在子线程中,将结构体的成员复制到局部变量或将它们保存在其他地方
在子线程中,向信号量发出信号
在父线程中,关闭信号量
如果这些是被喂养了数据的主题您可以使用共享存储器或全局变量,(如果没有其他需要这样的说法)或链表。
不过,别忘了锁定您的变量正在线程共享。
如果没有实际问题的代码,虽然,我不能告诉你,你在你的当前实现做错了什么。
此错误消息意味着你不取消引用指针。
您是说 “T.A” 而不是 “T->一个”
[me@myhost ~]$ cat testitx.c struct x { int a, b; }; int main(int argc, char *argv[]) { struct x y, *z; z = &y; z.a = 10; } [me@myhost ~]$ cc -c testitx.c testitx.c: In function `main': testitx.c:10: error: request for member `a' in something not a structure or union [me@myhost ~]$
我经常用来在其他的答案中所列的同样的错误,但现在我需要一个稍微不同的方法,移动潜在的错误从线程函数pthread_create的的电话。
我声明和在“正常”的方式定义线程功能:
void *ThreadFunction(sPARAMETERS *Params) {
// do my threading stuff...
}
和当我调用pthread_create,我需要使用流延:
pthread_create(&ThreadId,0,(void*(*)(void*)) &ThreadFunction,&Params);
我几乎从来不忘记使用和存在params,编译器将采取的我把另一端的任何错误的照顾。伟大工程回调,太
my_struct富=(my_struct)(* ARG);是incoreect 尝试 my_struct *富=(my_struct *)(ARG);结果 AND,诠释函数调用线程, 确保其静态(所以存储器所指向,在雾中不丢失)