semaphores do not access like volatile

Lex Spoon lex at cc.gatech.edu
Thu Feb 13 20:18:29 UTC 2003


Niko Schwarz <niko.schwarz at gmx.net> wrote:
> Is there a way to make semaphore behave non-remembering?

Bottom line: don't fuss with such low-level mechanisms!

The simple thing of immediately losing a signal won't work due to race
conditions.  You need to combine it with a mutex, which starts getting
complicated.  (I'll describe that in a second).  Otherwise, you can do a
simple thing of drain a semaphore entirely when a signal arives.  That
is, after you do "semaphore wait", follow it by "semaphore initSignals".
 You have to be very careful, by the way, that you check for *multiple*
events arriving, if you do this.

Anyway, something they teach at Georgia Tech (and I presume every where
else) is the combination of a condition variable and a mutex.  A
condition variable is a semaphore with no memory -- it only wakes up
people who are waiting on it.  A mutex is a lock (MUTual EXclusion). 
Using them is tricky.  I think the watcher looks like this, off the top
of my head:

	mutex lockDuring: [
		[ "check if stuff is ready" ] whileFalse: [ 
			mutex unlockAndWaitOn: condtionVariable ].
		"extract some stuff"
	].

And the signaller looks like this:
	
	mutex lockDuring: [
		"make stuff happen..."
		conditionVariable signal ]

The mutex is necessary in both cases because of the shared state.  Also,
you have to be very careful that you don't signal the thing outside of
the mutex, or the watcher may go to sleep and miss an event.


In comparison, look what it is with message queues.  The watcher does
this:

	queue next.


The sender does this:

	queue nextPut: whatever


Come on, why fuss with the nitty gritty stuff?  The only cost to using
message passing is that you have to eliminate shared state.  But, this
usually isn't *that* hard.

I agree that a timeout on SharedQueue's #next method would be nice.

-Lex


PS -- people who have been here very long, know that I truly think you
should get rid of the threads altogether!  You really need tool support
to do it better than a single-threaded support.  The initial extra
complexity from the single-threaded version, is usually dwarfed by the
complexities of synchronizing multiple threads.



More information about the Squeak-dev mailing list