Jar*_*316 6 c multithreading pthreads
我试图将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);
Run Code Online (Sandbox Code Playgroud)
在调用pthread_create之前,dim.width和dim.height是正确的.在我的套接字文件中,只设置了宽度,高度为0,我不明白为什么.
有谁知道什么是错的,请问如何解决?
非常感谢你.
Ada*_*eld 11
传递参数的方式应该可以正常工作,只要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);
Run Code Online (Sandbox Code Playgroud)