将多个参数传递给C中的线程(pthread_create)

我试图将2个无符号整数传递给C中新创建的线程(使用pthread_create())但是也没有2个整数或结构的数组似乎可以工作。

// In my socket file struct dimension { unsigned int width; unsigned int height; }; unsigned int width, height; void setUpSocket(void* dimension) { struct dimension* dim = (struct dimension*) dimension; width = dim->width; height = dim->height; printf("\n\nWidth: %d, Height: %d\n\n", width, height); } // In main.cpp // Pass a struct in pthread_create struct dimension dim; dim.width = w; dim.height = h; pthread_create(&ph, &attr, (void * (*)(void *)) setUpSocket, (void *) &dim); 

在调用pthread_create之前,dim.width和dim.height是正确的。 在我的套接字文件中,只设置了宽度,高度为0,我不明白为什么。

有谁知道什么是错的请问以及如何解决?

非常感谢你。

只要没有在堆栈上分配dim ,传递参数的方式应该可以正常工作。 如果它在堆栈上,那么它可能在新线程有机会运行之前被解除分配,从而导致未定义的行为。 如果您只创建一个线程,则可以使用全局变量,但更好的选择是在堆上分配它。

此外,您应该转换函数指针:这是未定义的行为(事实上, 它可能会因IA64架构上的推测性执行而崩溃 )。 您应该声明您的线程过程返回void*并避免函数指针强制转换:

 void *setUpSocket(void* dimension) { struct dimension* dim = (struct dimension*) dimension; width = dim->width; height = dim->height; // Don't leak the memory free(dim); printf("\n\nWidth: %d, Height: %d\n\n", width, height); return 0; } // In main.cpp // Pass a struct in pthread_create (NOT on the stack) struct dimension *dim = malloc(sizeof(struct dimension)); dim->width = w; dim->height = h; pthread_create(&ph, &attr, setUpSocket, dim); 

宽度和高度有多大? 如果不是很大,我会做这样的事情:

  pthread_create(&ph, &attr, setUpSocket, (void *)(65536*height+width)); 

您正在传递指向具有本地范围的变量的指针。 如果调用者函数在线程获取值之前完成,那么该变量将超出范围,并且其内容将是未定义的。

您在堆栈上创建该参数结构,该结构是临时存储,并由函数调用链重用。 它可能在线程启动时被覆盖。 您需要将指针传递给静态或堆分配的内存。