微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将多个参数传递给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);

原文地址:https://www.jb51.cc/c/111593.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐