Ok, so I am reading about synchronization, and I read through various algorithms such as spinlocks, semaphores, and mutex to avoid race condition.
However, these alg
You can prevent this using atomic instructions like TLS and XCHG.
How do you ensure atomicity for an instruction?
You can disable all interruptions before executing the instruction, then enable them all after the instruction is done. That doesn't help on multicore systems, because disabling the interruption in processor 1 doesn't have any effect on processor 2. On multicore systems the atomicity of an instruction is ensured by preventing other CPU's from access to the memory bus (memory barrier).
So, if you implement semaphores using these instructions you'll have no problems on SMP.
Implementation of mutex_lock and mutex_unlock using TSL:
mutex_lock:
TSL REGISTER, MUTEX ; copy mutex to register and sets mutex
CMP REGISTER, #0 ; compare mutex to zero
JZE ok ; if zero return
CALL thread_yield ; else: mutex is busy, schedule another thread
JMP mutex_lock ; try again later
ok: RET
mutex_unlock:
MOVE MUTEX,#0 ; free mutex
RET
You can find some information about TSL here: http://en.wikipedia.org/wiki/Test-and-set
A good book that can help you with: http://www.amazon.com/Modern-Operating-Systems-Andrew-Tanenbaum/dp/0136006639/ref=sr_1_sc_1?ie=UTF8&qid=1319333818&sr=8-1-spell