Page 1 of 1

Multi-core Mutex

Posted: Tue Oct 23, 2012 11:52 am
by Dennis
Hello everyone,

I just thought about the fact that when a program within an OS, on a multi-core CPU, is requesting an mutex (e.g. for writing to HDD) this could possibly leak.
For example, this is how the mutex gets requested (pseudocode):

Code: Select all

m = getCurrentMutexState();
if( isNotUsed( m ) ){
 setMutexUsed( m );
 /* code here */
 setMutexUnused( m );
}
tryAgain();
It could leak when the following happens (they are both requesting the same mutex):

Code: Select all

CORE1: core1m=getCurrentMutexState(); // not in use
CORE2: core2m=getCurrentMutexState(); // not in use
CORE1: if( isNotUsed(core1m) ) // not in use, so continue
CORE2: if( isNotUsed(core2m) ) // still not set as used
CORE1: setMutexUsed( core1m ) // now it is in use
CORE2: setMutexUsed( core2m ) // it was in use, still in use
etc.
As you can see, if both CPU cores are requesting the same mutex (flag in memory) at the same time, what is quite unlikely but definitely possible, they are both continuing like they have the mutex, which could result in serious problems for the OS.

Now I was wondering how this is being solved in nowadays OS's, or how you should solve this.

Thanks,
Dennis

Re: Multi-core Mutex

Posted: Tue Oct 23, 2012 11:54 am
by Nessphoro
Bus locking with LOCK instruction prefix

Re: Multi-core Mutex

Posted: Tue Oct 23, 2012 12:25 pm
by Antti
This is a race condition. It is easy to solve if an instruction can do test and set atomically. For x86 family, there is BTS instruction. Remember to use LOCK prefix and you are safe.

Re: Multi-core Mutex

Posted: Tue Oct 23, 2012 3:07 pm
by OSwhatever
If you are using GCC, the atomic built-in function are quite handy.

http://gcc.gnu.org/onlinedocs/gcc-4.1.1 ... ltins.html

For semaphore and mutexes the atomic add and sub would be useful.

Re: Multi-core Mutex

Posted: Tue Oct 23, 2012 6:16 pm
by Combuster
You won't be writing your own threading code if you don't know how to use the tools for the job, and you apparently don't even know about the basic solutions like Dekker's algorithm. The entire subject is worth several books full, so get reading.