简体   繁体   中英

Passing multiple arguments to a thread in C (pthread_create)

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

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?

Thank you very much.

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.

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

How big can width and height be? If not very big, I would do something like this:

 pthread_create(&ph, &attr, setUpSocket, (void *)(65536*height+width));

You are passing a pointer to a variable with local scope. If the caller function finishes before the thread has picked up the values, then that variable will go out of scope, and its contents will be undefined.

You creating that argument structure on the stack, which is temporary storage and is re-used by the function call chain. It's probably overwritten by the time the thread starts. You need to pass a pointer to either static or heap-allocated memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM