传递多个参数给一个线程在C(pthread_create的) [英] Passing multiple arguments to a thread in C (pthread_create)

查看:607
本文介绍了传递多个参数给一个线程在C(pthread_create的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过2无符号整数,在C新创建的线程(使用在pthread_create()),但也不是2个整数数组或结构似乎工作。

I am trying to pass 2 unsigned integers to a newly created thread in C (using pthread_create()) but nor an array of 2 integers or a struct seems to work.

// 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,我不明白为什么。

Before calling pthread_create, dim.width and dim.height are correct. In my socket file, only width is set, height is 0, and I do not understand why.

有谁知道什么是错了,请和如何解决它?

Does anyone know what is wrong please and how to fix it?

非常感谢你。

推荐答案

你传递的参数应该做工精细的方式,只要昏暗是在堆栈上未分配即可。如果是在栈上,那么它可以在新的线程有机会运行,造成不确定的行为成为前释放。如果你只创建一个线程,你可以使用全局变量,但更好的方法是分配它在堆上。

The way you're passing the arguments should work fine, as long as dim is not allocated on the stack. If it's on the stack, then it could become deallocated before the new thread has a chance to run, resulting in undefined behavior. If you're only creating one thread, you can use a global variable, but the better alternative is to allocate it on the heap.

此外,你应该的的被铸造的函数指针:这是未定义的行为(事实上,的it可能会崩溃,由于在IA64架构推测执行)。你应该声明你的线程过程返回无效* ,避免函数指针转换:

Also, you should not be casting the function pointer: that is undefined behavior (and in fact, it could crash due to speculative execution on the IA64 architecture). You should declare your thread procedure to return void* and avoid a function pointer cast:

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);

这篇关于传递多个参数给一个线程在C(pthread_create的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆