pthreads in C - pthread_exit

前端 未结 9 1253
北荒
北荒 2021-02-05 14:03

For some reason I thought that calling pthread_exit(NULL) at the end of a main function would guarantee that all running threads (at least created in the main funct

相关标签:
9条回答
  • 2021-02-05 14:34

    When you pass a thread a pointer to a variable, you need to ensure that the lifetime of that variable is at least as long as the thread will attempt to access that variable. You pass the threads pointers to buffer and context, which are allocated on the stack inside main. As soon as main exits, those variables cease to exist. So you cannot exit from main until you confirm that those threads no longer need access to those pointers.

    95% of the time, the fix for this problem is to follow this simple pattern:

    1) Allocate an object to hold the parameters.

    2) Fill in the object with the parameters.

    3) Pass a pointer to the object to the new thread.

    4) Allow the new thread to deallocate the object.

    Sadly, this doesn't work well for objects shared by two or more threads. In that case, you can put a use count and a mutex inside the parameter object. Each thread can decrement the use count under protection of the mutex when it's done. The thread that drops the use count to zero frees the object.

    You would need to do this for both buffer and context. Set the use count to 2 and then pass a pointer to this object to both threads.

    0 讨论(0)
  • 2021-02-05 14:37

    pthread_exit(3) exits the thread that calls it (but not the whole process if other threads are still running). In your example other threads use variables on main's stack, thus when main's thread exits and its stack is destroyed they access unmapped memory, thus the segfault.

    Use proper pthread_join(3) technique as suggested by others, or move shared variables into static storage.

    0 讨论(0)
  • 2021-02-05 14:42

    pthread_join() is the standard way to wait for the other thread to complete, I would stick to that.

    Alternatively, you can create a thread counter and have all child threads increment it by 1 at start, then decrement it by 1 when they finish (with proper locking of course), then have your main() wait for this counter to hit 0. (pthread_cond_wait() would be my choice).

    0 讨论(0)
提交回复
热议问题