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

此外,您不应该转换函数指针:这是未定义的行为(事实上,it could crash due to speculative execution on the IA64 architecture).您应该声明您的线程过程返回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);

    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,setUpSocket,dim);

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...