1/5
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Semaphore
Synchronization primitive based on a shared integer counter. P decrements when positive only and V increments.
Why use semaphores?
can do mutual exclusion but no ownership principle
task coordination
Signal between tasks
resource availability
Reader-Writers problem
Many tasks can access a shared resource at a time. Some read, some write. When writing, no other task can read or write.
Multiple readers allowed, but not multiple writers or both.
Readers-writers Solution
Use:
Reader semaphore for readcount (init to 1)
Writer semaphore for writing (init to 1)
reader count = 0 initially
Readers:
Lock reader semaphore
Increment reader count
If first reader to enter, lock the writer semaphore
Unlock reader semaphore and read
Lock reader semaphore to update reader count
If last reader, unlock writer semaphore
Unlock reader semaphore
Writers:
Unlock writer semaphore
Write
Lock writer semaphore
Semaphore functions
sem_wait(sem_t *sem): Post/decrement operation
sem_post(sem_t * sem): Increment operation
sem_init(sem_t *sem, int pshared, unsigned int val): Init semaphore to value val. pshared = 0 means thread shareable versus process shareable
sem_destroy(sem_t *sem) deallocate semaphore
Create a named semaphore
To use a semaphore across independent executables (processes)
const char* SEM_NAME
sem_t *sem = sem_open(SEM_NAME, O_CREAT, 0666, 1)