pthread_cond_timedwait is a nice little function that can be used to “atomically” release a mutex, wait for a condition with a timeout and then acquire the mutex. The first pitfall of this method is that the “timeout” is an absolute time, not a relative time as with most timeouts. Other than that it works fine for most platforms I’ve encountered. Until I used it on a BSD based system. Suddenly the code did not work in some cases. I managed to track it down to the situation where the time had already passed in which case I got odd behavior.
Turns out most platforms implement this method in a way so that if the time have passed, the mutex is released and reacquired immediately (an assumption used in the code I was working on), but on BSD this is not the case. For most platforms the MAN-page clearly states that this is the case (i.e. release and reacquire the mutex) but for BSD it says nothing about it. I can only assume there is an optimization in the code skipping the release-reacquire action if the time have already passed. I think that is an odd behavior since it blocks any other threads waiting for that mutex (unless you work around it with an extra release-acquire scheme).
So know your APIs and be careful if you’re writing code for several platforms. And I can ensure that a number of unit tests exploring the behavior of an API can save time trouble shooting differences like this.