How to return a value from pthread threads in C?

后端 未结 8 2226
没有蜡笔的小新
没有蜡笔的小新 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:45

    I think you have to store the number on heap. The int ret variable was on stack and was destructed at the end of execution of function myThread.

    void *myThread()
    {
           int *ret = malloc(sizeof(int));
           if (ret == NULL) {
               // ...
           }
           *ret = 42;
           pthread_exit(ret);
    }
    

    Don't forget to free it when you don't need it :)

    Another solution is to return the number as value of the pointer, like Neil Butterworth suggests.

提交回复
热议问题