我尝试将结构作为第四个参数传递,同时使用pthread_create()
如下内容:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
现在,每当我尝试访问结构中的变量 - ta、tb 或 tc 时,我都会不断收到错误消息 - 请求非结构或联合中的成员。
我可以使用什么替代方法将结构传递到线程中?
我尝试将结构作为第四个参数传递,同时使用pthread_create()
如下内容:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
现在,每当我尝试访问结构中的变量 - ta、tb 或 tc 时,我都会不断收到错误消息 - 请求非结构或联合中的成员。
我可以使用什么替代方法将结构传递到线程中?
您可能在与 pthread_create 相同的范围内创建结构。一旦退出该范围,此结构将不再有效。
尝试在堆上创建一个指向结构的指针并将该结构指针传递给您的线程。不要忘记在某处删除该内存(如果您再也不会使用它,或者当您不再需要它时,请在线程中删除它)。
此外,正如cyberconte 所提到的,如果您要从不同的线程访问该数据,则需要使用互斥锁或临界区锁定对它的访问。
编辑 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 */
}
或者,如果您将指针传递给您的结构:
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,等待信号量
在子线程中,将结构的成员复制到局部变量或将它们保存在其他地方
在子线程中,发出信号量
在父线程中,关闭信号量
您可以使用共享内存或全局变量(如果没有其他东西需要该参数)或链表,如果这些线程是数据馈送。
请记住锁定线程共享的变量。
但是,如果没有实际的违规代码,我无法告诉您在当前实现中做错了什么。
此错误消息意味着您没有取消引用指针。
你说的是“ta”而不是“t->a”
[me@myhost ~]$ cat testitx.c 结构 x { 整数a,b; }; int main(int argc, char *argv[]) { 结构 xy, *z; z = &y; za = 10; } [我@myhost ~]$ cc -c testitx.c testitx.c:在函数“main”中: testitx.c:10:错误:在不是结构或联合的东西中请求成员“a” [我@我的主机~]$
我以前经常犯其他答案中列出的相同错误,但现在我采取了一种稍微不同的方法,将潜在的错误从线程函数转移到 pthread_create 调用。
我以“正常”方式声明和定义线程函数:
void *ThreadFunction(sPARAMETERS *Params) {
// do my threading stuff...
}
当我调用 pthread_create 时,我需要使用演员表:
pthread_create(&ThreadId,0,(void*(*)(void*)) &ThreadFunction,&Params);
我几乎永远不会忘记在参数上使用 &,编译器会处理我在另一端犯的任何错误。也适用于回调。
my_struct foo = (my_struct)(*arg); 是 incoreect try my_struct *foo = (my_struct *)(arg);
并且,int 调用线程的函数,确保它是静态的(所以指向的内存不会迷失在迷雾中)
这是一个例子:这个函数将创建线程并传递结构参数
pthread_create (& threads[i], NULL , PrintMessage ,(void *) &tab[i]);
这是线程函数:
void *PrintMessage(void * arg)
{
struct param *mes_param ; mes_param = (struct param*) arg;
printf (" message from thread %d: %s\n", mes_param -> num_message ,
mes_param -> message );
pthread_exit(NULL);
}
结构:
struct param {
int num_message ;
char* message ; };
struct param tab[MAX_THREADS];