Multi-core Mutex

Discussions on more advanced topics such as monolithic vs micro-kernels, transactional memory models, and paging vs segmentation should go here. Use this forum to expand and improve the wiki!
Post Reply
Dennis
Posts: 7
Joined: Sun Jan 22, 2012 12:31 pm

Multi-core Mutex

Post 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
User avatar
Nessphoro
Member
Member
Posts: 308
Joined: Sat Apr 30, 2011 12:50 am

Re: Multi-core Mutex

Post by Nessphoro »

Bus locking with LOCK instruction prefix
Antti
Member
Member
Posts: 923
Joined: Thu Jul 05, 2012 5:12 am
Location: Finland

Re: Multi-core Mutex

Post 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.
OSwhatever
Member
Member
Posts: 595
Joined: Mon Jul 05, 2010 4:15 pm

Re: Multi-core Mutex

Post 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.
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

Re: Multi-core Mutex

Post 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.
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
Post Reply