[Newbies] Re: Semaphore problems

Ron Teitelbaum Ron at USMedRec.com
Sun Sep 30 02:20:25 UTC 2007

Hi Jason,

I’m not really sure what you are trying to do but this works too.

semA := Semaphore forMutualExclusion.
semB := Semaphore new.

[semA critical: [Transcript show: 'b1'; cr. semB signal. semA wait.].

	Transcript show: 'b2'; cr.
	semB signal.	
] fork.
[semB critical: [Transcript show: 'a1'; cr. semA signal. semB wait.].
	Transcript show: 'a2'; cr.
] fork.

Semaphore forMutualExclusion signals the semaphore so that you can get into
the first critical block.

The critical block is what does the code blocking.  

SemB signal allows the second thread in while semA wait keeps the block from
Then semA signal allows the first block to continue, but semB wait keeps the
second block from exiting.  
Then semB signal allows the second block to continue, and since both forked
blocks complete they disappear.

There are a lot of ways to make this easier, but I think it’s good to look
at these constructs closely, if you are planning to work with threads.

Check out SharedQueue for thread safe processing.  Also have a look at Mutex
for other Semaphore behavior.

Good luck!

Ron Teitelbaum
President / Principal Software Engineer 
US Medical Record Specialists

From: Jason Shoemaker

This is probably a safer version.  It works for me.

semA := Semaphore new.
semB := Semaphore new.

thread1 := [Transcript cr; nextPutAll: 'b1'. semB signal. semA wait.
        Transcript cr; nextPutAll: 'b2'. ] fork. 
thread2 := [Transcript cr; nextPutAll: 'a1'. semA signal. semB wait.
        Transcript cr; nextPutAll: 'a2'.] fork.

[thread1 isTerminated and: [thread2 isTerminated]] whileFalse: 
    [(Delay forMilliseconds: 100) wait]. 
Transcript flush

Now to move on to another pattern.


More information about the Beginners mailing list