On 02/16/2010 08:19 PM, Caleb Clausen wrote:
> On 2/16/10, Robert Klemme <shortcutter / googlemail.com> wrote:
>> 2010/2/15 Caleb Clausen <vikkous / gmail.com>:
>>> It depends on what you're using the semaphore for. If it's to be used
>>> for locking, you're right. If it's a signaling semaphore, then 0 for
>>> the init value is exactly what's needed.
>> Right you are.  Although I'd say that a condition variable is probably
>> a better tool for that.
> 
> It may be, but I've never understood condition variables properly.
> They seem to be semaphores with some additional semantics but it never
> made enough sense to me that I felt I could use them with
> confidence... the docs never helped. I was raised on semphores, and
> that's all I know. :) If you actually understand condition variables
> and how to use them, could you kindly explain them to me? I would be
> grateful.

Ah, my posting did not make it through the gateway - probably because I 
attached the code.  Here it is again: http://gist.github.com/305986

Basically a condition variable is just a special signaling mechanism - 
you can use any number of condition variables with a mutex or monitor in 
order to signal different conditions.  Waiting threads are then woken up 
efficiently.  For example, in a bounded queue you can have two condition 
variables @queue_has_room and @data_available with obvious semantics 
(@queue_has_room is signaled whenever something is taken from the queue, 
@data_available is signaled whenever something is put into the queue).

Technically when you wait on a condition variable you must own the 
monitor / mutex.  Your thread is blocked and the lock is released.  When 
a signal occurs for this condition variable, waiting threads are woken 
and after the signal thread releases the lock any of the waiting thread 
obtains it and continues.  That way you can selectively wake up threads 
which is more efficient to just wake up all threads waiting for a monitor.

If you want to dig deeper into concurrency I can recommend Doug Lea's 
excellent book (even though it is about Java). http://g.oswego.edu/

Kind regards

	robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/