If the caller of sem_post() wakes up a thread sleeping via sem_wait()
before it clears the has_waiters flag, the caller of sem_wait() has no way of
knowing when it is safe to destroy the semaphore and reuse the memory. This is
because the caller of sem_post() may be interrupted between the wake step and
the clearing of has_waiters. It will then write into the has_waiters flag in
userspace after being preempted for some unknown amount of time.
A test program that illustrates the issue I want to fix is here:
This program can sometimes exit in the otherfunc() function printing
"sem struct changed after yielding". There is a README.txt file in that
same directory describing the test in more detail.