How to return a value from pthread threads in C?

后端 未结 8 2209
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:16

I\'am new to C and would like to play with threads a bit. I would like to return some value from a thread using pthread_exit()

My code is as follows:

8条回答
  •  情深已故
    2020-11-27 03:36

    You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

    void *myThread()
    {
       return (void *) 42;
    }
    

    and then in main:

    printf("%d\n",(int)status);   
    

    If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.

提交回复
热议问题