I’m trying to implement mutexes inside my standard library but I’m not getting anywhere with them. I know that it is a bad idea to try to implement something that you do not necessarily understand, but I have to, since compiling an existing threading library (such as uClibc) is impossible for this platform. Are there any “explain it to me like I’m 5” things for mutexes? Or are there any “simple to follow” implementations? All of the pthread implementations I’ve seen so far are impossible to follow.
My implementation of the locking function is provided below. I’m pretty sure there is something seriously wrong with it, since I have no idea what I’m doing.
int pthread_mutex_lock(pthread_mutex_t *pmutex)
{
OSMutex* mutex = GetOSMutex(pmutex);
/* Decrement the mutex counter */
OSAtomicDecrement32(&(mutex->count));
if (mutex->count < -1) {
/*
Contended, wait for the mutex to be released.
*/
lnkLog("mutex %p already held (n=%d), waiting for stuff to change", mutex, mutex->count);
futex$LINUX(&(mutex->data),
FUTEX_WAIT,
MUTEX_MAGIC,
NULL,
NULL,
0);
lnkLog("mutex %p was released", mutex);
return 0;
}
else {
/*
Not contended. Acquire the mutex.
*/
lnkLog("locking %p", mutex);
mutex->data = MUTEX_MAGIC;
return 0;
}
}
P.S. If you’re wondering about the futexes, I’m using the Linux kernel.
http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html
Look into __sync_lock_test_and_set
You have to have hardware support for doing atomics. GCC builtins are a good start.