mdsplus icon indicating copy to clipboard operation
mdsplus copied to clipboard

Dont use pthread_cancel in Windows code.

Open zack-vii opened this issue 4 years ago • 0 comments

Windows' mapping of the pthread library is incomplete. In particular the pthread_cancel wont cancel your thread. Trusting that it will, may cause Windows programs to deadlock e.g. with a subsequent pthread_join. Thus we need to design our threads such that we have manual cancellation points.

The cancellation point could be:

  1. An "atmomic" flag variable that is cleared before thread creation, passed as argument and stored aside the pthread_t variable. The thread should periodically checked it and trigger graceful termination if set (break out of loops, or call pthread_exit()).

  2. In threads with file descriptor IOs the flag could be a eventFd (cheaper than a pipe). to test in normal code section a non-blocking poll can be performed to check for a cancellation request. Instead of performing a blocking read of write (with long or no timeout) one should use a select on the actual fd and the eventfd. The thread shall gracefully terminate if it can read at least on byte or the eventfd was closed. (You sould set the event by sending a dummy byte (for eventFd, set the value to max i.e. ((uintptr_t)-2).)

  3. None of the mutex functions is a cancellation point, not even pthread_mutex_lock. (avoid such deadlocks in general, helgrind should help preventing that)

  4. When waiting for a pthread_condition_t always use the timed version checking for both the condition in question or the cancellation event.

If you have more typical traps please extent this issue.

zack-vii avatar May 07 '21 08:05 zack-vii