bkilgore wrote:
I just did this recently because I was having a problem with printing to the screen where if I had two threads running, both printing to the screen (say process A printing the alphabet over and over and process B printing dots) then sometimes I would get the . overwriting one of the characters because of the race condition. By adding a spinlock around the code that updates the screen location it now works correctly, always sticking the . between two letters.
So basically, all you really have to do in a uniprocessor system is make sure interrupts are disabled,
I would definately recommend against this, if system responsiveness to interrupts is at all an issue for you. You can get the same protection using semaphores or mutexes without having to have interrupts disabled during the entire protected section. So, for example, instead of disabling interrupts while writing to the screen, one should acquire a screen mutex, write to the screen, and release the mutex. Interrupts are only disabled for a few instructions inside the acquireMutex and releaseMutex functions. This gives you the same protection without locking out interrupts for the entire time you're in the protected section.
Really, the ONLY things that ought to be protected by a spinlock are your semaphore and mutex functions. Everything else should be protected by a semaphore or mutex. This dramatically reduces the amount of spinning your system will do -- instead, it just finds another task to execute while one is waiting to enter a critical section.