Semaphore and Spinlock

Jeff Haran Jeff.Haran at citrix.com
Mon Apr 27 12:31:01 EDT 2015


> -----Original Message-----
> From: kernelnewbies-bounces+jharan=bytemobile.com at kernelnewbies.org
> [mailto:kernelnewbies-
> bounces+jharan=bytemobile.com at kernelnewbies.org] On Behalf Of
> Abhishek Bist
> Sent: Monday, April 27, 2015 6:19 AM
> To: kernelnewbies at kernelnewbies.org
> Subject: Semaphore and Spinlock
> 
> [ Semaphores are a bit like spinlocks, except the holder of a semaphore is a
> process, not a CPU. ] This is a very first line that is bein written on the
> description of semaphore on kernel newbies.So what are the different
> parameter that could justify this statement or the way it could be justified
> and understood.

It makes sense to me conceptually. Say you are running some kernel code on a multicore system and that code serializes access to some data structure via a spinlock. If core A takes the spinlock, then core B comes along and tries to take it, core B will spin until core A releases the spin lock, at which point core B will hold it. Conceptually, core B is prevented from doing anything else while core A holds the spinlock.

Now say you are running some kernel code that is executed in the context of multiple processes and that code serializes access to some data structure via a semaphore. If process A takes the semaphore, then process B comes along and tries to take it, process B will block (the core B is running on will do a context switch to some other process) until process A releases the semaphore, at which point process B will hold it and once the scheduler on B's core allows process B will start running again. Conceptually, process B is prevented from doing anything else while process A holds the semaphore. A mutex here would also apply.

Semaphore is to process like spinlock is to core, at least in this case where the semaphore is being used for mutual exclusion.

Jeff Haran




More information about the Kernelnewbies mailing list