Page 1 of 1

Mutual exclusion

Posted: Mon Jun 16, 2003 12:23 am
by Ozguxxx
Hi, I am stuck at this multithreading thing -yes, its been about two and a half months and I am still here at the same place with no progress- I now have problem on mutual exclusion, more clearly, I am trying to avoid confusion when two threads call same function -so that they do not interfere with each other- certainly I need mutual exclusion, no I have two questions:
1) Do I have to add mutual exclusion code to all the functions that might be called by threads at the same time?
2) Can you give some hint on achieving this? ;D

Thanx... Unfortunately I could not get used to using the search function here, so I am sorry...

Re:Mutual exclusion

Posted: Mon Jun 16, 2003 5:34 am
by Pype.Clicker
you'll need to protect (through mutual exclusion) any piece of code that *must not* be called by several thread together. for instance, you clearly can't let 2 threads modify the "head of physical available pages list" in the mean time, or have one interrupted by another while it is modifying it.

Instead of protecting every call to the function like

Code: Select all

mutex.lock(memory);
x=memAlloc(size);
mutex.unlock(memory);
you should push protection *within* the protected function:

Code: Select all

addr_t* memAlloc(size_t s) {
   mutex.lock(memory);
   <alter state>
   mutex.unlock(memory);
}
So there's less risk you forget to protect one function than one function call.

Also remember to unlock stuff even in the case of unexpected event (and early procedure return).