我尝试在使用pthread_create()
时将结构体作为第四个参数传递,代码如下:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
现在每当我尝试访问结构体中的变量 - t.a,t.b或t.c时,都会出现错误 - 请求在非结构体或联合体中的成员。我应该使用什么替代方法来将结构体传递到线程中?
我尝试在使用pthread_create()
时将结构体作为第四个参数传递,代码如下:
pthread_create(&tid1, NULL, calca, &t); //t is the struct
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* 类型。在使用之前,需要将其转换为 struct。
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的线程中,等待信号量
在子线程中,将结构体成员复制到本地变量或其他位置保存
在子线程中,发出信号量
在父线程中,关闭信号量
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];
我以前经常犯其他答案中列出的相同错误,但现在我采取了稍微不同的方法,将潜在的错误从线程函数移动到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); 是不正确的
尝试使用 my_struct *foo = (my_struct *)(arg);
并且,在调用线程的函数中,
确保它是静态的(这样指向的内存不会在迷雾中丢失)
如果没有其他东西需要该参数,您可以使用共享内存或全局变量。或者,如果这些是依赖数据的线程,则可以使用链表。
只需记住锁定正在进行线程共享的变量即可。
但是,如果没有实际的有问题代码,我就无法告诉您当前实现中出了什么问题。
这个错误信息意味着您没有对指针进行解引用。
您应该使用"t->a"而不是"t.a"
[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 ~]$