mmap
with
MAP_SHARED
).data
segment (if initialized)static
keyword)static
specifierA more general primitive
A semaphore - just an integer with some ops associated
A lock (mutex) is just a special case of a semaphore
Idea: if the semaphore is 0
, we have to wait, if the
semaphore > 0
, we’re good to go
sem_init
- initialize a semaphore
sem_wait
- waits for semaphore to become != 0,
decrements it by 1 atomically
sem_post
- increments semaphore by one
atomically
If we want the semaphore to be shared, we need to allocate it as a shared variable
Example - using a semaphore as a lock (max value 1)
sem = 1
proc A proc B sem
sem_wait(sem) 1
do_work(); sem_wait(sem); 0 // sem_wait blocks in B
do_more_work(); . 0
. . 0
. . 0
. . 0
sem_post(sem); . 1 // sem_wait returns in B
. do_work(); 0
sem_wait(sem); do_more_work(); 0 // sem_wait blocks in A
. . 0
. sem_post(sem); 1 // sem_wait returns in A
do_work(); . 0
See sum_semaphores.c
Try
$ time ./sem-sum
and observe how much time is spent in the kernel. Compare this to the other versions
Semaphores with higher values are used, for example, for counting resources
mmap
has an option to allocate a shared piece of
memory