I"ve been using semaphores to lock my data which is used in different
threads. I chose semaphores over mutexs, as semaphores let you try a
lock, without blocking the thread if you like (SDL_SemTryWait()).
I understand SDL_SemWait() and SDL_SemTryWait(), will decrement the
semaphore if they manage to lock the resource, and SDL_SemPost() will
increment it. Now will SDL_SemPost() increment the semaphore if it
wasn’t locked previously? ie if I call SDL_SemPost() twice will it
increment the semaphore twice, and as such mess up future attempt to
It should, because semaphore are much more flexible that mutex and are not
only designed for critical section.
The standard printer allocation problem (see a good concurency book for
reference) uses the fact that semaphores counts.
You see I’m initialising the semaphores with a value of ‘1’, and when
locked it goes to ‘0’. Are there any other ways this semaphore may
deviate from this range?
When you lock, it decrements, and when it is lower or equal to zero, it puts
your threads in a blocked thread queue. When you unlock, if the counter is
lower or equal to zero, the heading process of the blocked process queue is
Here is an example of semaphore implementation (we assume that there is no
concurent access while in semaphore)
The following example is in Modula 2 pseudo code and is taken from the book
"Programmation Concurente", from Andre Schiper, PPUF
procedure P is lock
procedure V is unlock
( standard Dikstra original way to speak )
type semaphore = record
waiting_queue : thread list;
procedure P(var s:semaphore)
s.n := s.n - 1;
if (s.n < 0) then
block current thread into s.waiting_queue
procedure V(var s:semaphore)
s.n := s.n + 1;
if (s.n <= 0) then
unblock the heading thread from s.waiting_queue
Also if you’ve got some data that doesn’t change (possibly const data),
do you still have to lock it, between threads, just to read it?
No, you need to protect data for consistency when concurent writing or