How to return a value from pthread threads in C?

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

    Question : What is the best practice of returning/storing variables of multiple threads? A global hash table?

    This totally depends on what you want to return and how you would use it? If you want to return only status of the thread (say whether the thread completed what it intended to do) then just use pthread_exit or use a return statement to return the value from the thread function.

    But, if you want some more information which will be used for further processing then you can use global data structure. But, in that case you need to handle concurrency issues by using appropriate synchronization primitives. Or you can allocate some dynamic memory (preferrably for the structure in which you want to store the data) and send it via pthread_exit and once the thread joins, you update it in another global structure. In this way only the one main thread will update the global structure and concurrency issues are resolved. But, you need to make sure to free all the memory allocated by different threads.

提交回复
热议问题