2009-01-04

Win32 threading API anomaly

I like to split my code into a series of simple helper functions. When developing for multithreaded environment, some of these functions have to be called while a certain mutex is held by the current thread. In POSIX, it's easy to test for a weaker condition, namely that the mutex is locked:

assert(pthread_mutex_trylock(&mtx) == EBUSY)

There is no way to check that the current thread holds the mutex. However, if another thread has locked the mutex, one may hope that pthread_mutex_unlock will return EPERM error code (I don't think that the pthread library is obliged to check for every possible error condition).

Take Win32, and the TryEnterCriticalSection function which returns, according to the documentation: "If the critical section is successfully entered or the current thread already owns the critical section, the return value is nonzero. If another thread already owns the critical section, the return value is zero."

Since I actually expect that the current thread already owns the mutex, the "or" clause in the first sentence makes it impossible to implement even the (weaker) sanity check which is possible under POSIX. Kinda shame.

No comments: