Page 1 of 1

Mutex vs. Semaphore

Posted: Sat Aug 26, 2006 3:27 pm
by omin0us
So i am to the point that i have software based task switching.
and i have a couple tasks each printing separate things.
but i have noticed that in bochs (but not vmware) stuff being printed to the screen is messed up, sometimes only half of the the text to be printed actually gets printed. and other weird things. so my first idea was to just disable ints upon calling my kprintf. but someone told me that was a bad idea because it disables the cpu for a long time. they suggested mutex/semaphore.

but i am confused on what the difference is between the two.
also, what is non re-entrant code?

Re:Mutex vs. Semaphore

Posted: Sat Aug 26, 2006 3:47 pm
by Kemp
Non-reentrant code is basically code that can break if it is interrupted mid-execution and called again from another thread. A classic example would be if it uses global variables, in which case the second run would modify the ones the first run was using.

For the difference between mutexes and semaphores, try the OSFAQ

Re:Mutex vs. Semaphore

Posted: Mon Aug 28, 2006 6:58 am
by Pype.Clicker
bochs is sensibly slower than vmware ... and thus you have more chances to experience IRQs in a small portion of code.
so my first idea was to just disable ints upon calling my kprintf. but someone told me that was a bad idea because it disables the cpu for a long time
that'd somehow depend on how long your input strings to kprintf can be (okay, printf indeed supports arbitrarily long messages, but that doesn't necessarily mean kprintf should do the same, right ?)

What you probably want to protect is "where the 'cursor' is". Imagine you have your first thread 1) reading the current location, 2) writing to screen, then 3) updating cursor location. If it gets interrupted between steps 1) and 3), another thread may be writing to the same screen region, resulting in messed display.

There's a fairly simple solution, though:
1. compute your final string's size
2. lock interrupts
3. read cursor location and update it so that you have room to write your string
4. release interrupts
5. do the dull job of writing to the screen.