加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:24:18 所属栏目:百科 来源:网络整理
导读:我试图将2个无符号整数传递给C中新创建的线程(使用pthread_create())但是也没有2个整数或结构的数组似乎有效. // In my socket filestruct dimension { unsigned int width; unsigned int height;};unsigned int width,height;void setUpSocket(void* dimens
我试图将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("nnWidth: %d,Height: %dnn",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("nnWidth: %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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读