|
|
Class: Semaphore
Object
|
+--Semaphore
- Package:
- stx:libbasic
- Category:
- Kernel-Processes
- Version:
- rev:
1.83
date: 2010/02/05 12:58:06
- user: cg
- file: Semaphore.st directory: libbasic
- module: stx stc-classLibrary: libbasic
- Author:
- Claus Gittinger
Semaphores are used to synchronize processes providing a nonBusy wait
mechanism. A process can wait for the availability of some resource by
performing a Semaphore>>wait, which will suspend the process until the
resource becomes available. Signalling is done by (another process performing)
Semaphore>>signal.
If the resource has been already available before the wait, no suspending is
done, but the resource immediately allocated.
The resource internally keeps a count, the number of times the resource can be
allocated. If the semaphore is created with a count greater than 1, the sema
can be waited-upon that many times without blocking.
On the other hand, if initialized with a negative count, the semaphore
must be signalled that many times more often in order for a wait to not block.
In other words: whenever the semaphore has a count greater than zero,
the wait operation will proceed. Otherwise, it will block until the count has
been incremented by signal operations to be greater than zero.
There are also semaphores for mutual access to a critical region
(Semaphore>>forMutualExclusion and Semaphore>>critical:).
Additional protocol is provided for oneShot semaphores,
(#signalOnce) and for conditional signalling (#signalIf).
You can also attach semaphores to external events (such as I/O arrival or
timer events).
This is done by telling the Processor to signal the semaphore
under some condition.
See 'Processor>>signal:afterSeconds:', 'Processor>>signal:onInput:' etc.
See examples in doc/coding (found in the CodingExamples-nameSpace).
Warning/Note/Hint:
a Semaphore-forMutualExclusion does NEVER allow for the critical
region to be entered twice - NOT EVEN by the same process.
That means, that a recursive attempt to enter that section leads
to a deadlock.
Use a RecursionLock instead, to avoid this.
Hint:
now (Jul2002), Semaphores now allow for a negative count; this allows for
a sync-point to be implemented easily (i.e. to wait for multiple other processes
to arrive at a sync-point).
See examples.
[instance variables:]
count <SmallInteger> the number of waits, that will go through
without blocking.
Incremented on #signal; decremented on #wait.
waitingProcesses <OrderedCollection> waiting processes - will be served first
come first served when signalled.
lastOwnerID <SmallInteger> a debugging aid: set when count drops
to zero to the current processes id.
Helps in finding deadlocks.
name <String> a debugging aid: an optional userFriendly
name; helps to identify a semaphore easier.
SemaphoreSet
RecursionLock
Monitor
SharedQueue
Delay
Process
ProcessorScheduler
instance creation
-
forMutualExclusion
-
create & return a new semaphore which allows exactly one process to
wait on it without blocking. This type of semaphore is used
for mutual exclusion from critical regions (see #critical:).
Also see RecursionLock, to avoid deadlock in case of recursive entered
critical regions.
-
new
-
create & return a new semaphore which blocks until a signal is sent
-
new: n
-
create & return a new semaphore which allows n waits before
blocking
Compatibility-Squeak
-
isSignaled
-
-
waitTimeoutMSecs: milliSeconds
-
-
waitTimeoutSeconds: seconds
-
printing & storing
-
displayString
-
return a string to display the receiver - include the
count for your convenience
-
name
-
return the semaphores userFriendly name
-
name: aString
-
set the semaphores userFriendly name
private
-
addWaitingProcess: aProcess
-
add aProcess to the list of waiting processes.
all processes are ordered first-come-first-serve.
NOTE: must be called with blocked interrupts
-
removeWaitingProcess: aProcess
-
remove aProcess from the list of waiting processes
NO action if it is not in the list.
NOTE: must be called with blocked interrupts
-
wakeupWaiters
-
remove all waiting processes from the list of waiting processes
and resume them.
NOTE: Must be called when known that waitingProcesses is nonNil and
also with blocked interrupts
private-accessing
-
clear
-
clear the semaphores count
-
initSignals
-
set the count of the semaphore to zero.
provided for ST-80 compatibility.
-
setCount: n
-
set the count of the semaphore;
thats the number of possible waits, without blocking
queries
-
count
-
return the number of 'already-counted' trigger events.
Thats the number of waits which will succeed without blocking
-
lastOwnerId
-
return the processId of the last owning process
(the one which counted to zero).
May be very useful in debugging deadLock situations
-
numberOfWaitingProcesses
-
return the number of processes waiting on the receiver
-
waitingProcesses
-
return the processes waiting on the receiver
semaphoreSet interface
-
checkAndAddWaitingProcess: process
-
interface for SemaphoreSet.
If the semaphore is available, decrement it and return true.
Otherwise register our process to be wakened up once the semaphore is available
and return false.
ATTENTION: this must be invoked with OperatingSystem-interrupts-blocked.
signaling
-
signal
-
waking up (the first) waiter.
Q: should this be the highest prio waiter ?
-
signalForAll
-
signal the semaphore for all waiters.
This can be used for process synchronization, if multiple processes are
waiting for a common event.
-
signalIf
-
signal the semaphore, but only if being waited upon.
This can be used for one-shot semaphores (i.e. not remembering
previous signals)
-
signalOnce
-
wakeup waiters - but only once.
I.e. if the semaphore has already been signaled, this is ignored.
testing
-
isEmpty
-
ST80 compatibility - return true if there are no waiters
-
wouldBlock
-
return true, if the receiver would block the activeProcess
if a wait was performed. False otherwise.
Attention: if asked without some global lock (blockedInterrupts),
the returned value may be wrong right away.
waiting
-
consume
-
consume the resource without waiting.
This works even if the count is 0 (count may become negative).
Answer the new count afterwards
-
consume: n
-
consume the resource n times without waiting.
This works even if the count is 0 (count may become negative).
Answer the new count afterwards
-
critical: aBlock
-
evaluate aBlock as a critical region; the receiver must be
created using Semaphore>>forMutualExclusion
-
wait
-
wait for the semaphore
-
waitUncounted
-
wait for the semaphore; do not consume the resource
(i.e. do not count down)
-
waitWithTimeout: seconds
-
wait for the semaphore, but abort the wait after some time (seconds).
return the receiver if the semaphore triggered normal, nil if we return
due to a timeout.
The seconds-argument may be a float (i.e. use 0.1 for a 100ms timeout).
With zero timeout, this can be used to poll a semaphore (returning
the receiver if the semaphore is available, nil if not).
However, polling is not the intended use of semaphores, though.
If seconds is nil, wait without timeout.
-
waitWithTimeoutMs: milliSeconds
-
wait for the semaphore, but abort the wait after some time.
return the receiver if the semaphore triggered normal, nil if we return
due to a timeout.
With zero timeout, this can be used to poll a semaphore (returning
the receiver if the semaphore is available, nil if not).
However, polling is not the intended use of semaphores, though.
If milliSeconds is nil, wait without timeout.
two processes synchronizing on a sema:
|sema thread1 thread2|
sema := Semaphore new.
thread1 := [
Transcript showCR:'here is thread 1; now waiting ...'.
sema wait.
Transcript showCR:'here is thread 1 again.'.
] newProcess.
thread2 := [
Transcript showCR:'here is thread 2; delaying a bit ...'.
Delay waitForSeconds:5.
Transcript showCR:'here is thread 2 again; now signalling the sema'.
sema signal.
Transcript showCR:'here is thread 2 after the signalling.'.
] newProcess.
thread1 priority:7.
thread2 priority:6.
thread1 resume.
thread2 resume.
|
semaphore for critical regions:
|accessLock|
accessLock := Semaphore forMutualExclusion.
[
5 timesRepeat:[
Delay waitForSeconds:2.
accessLock critical:[
Transcript showCR:'thread1 in critical region'.
Delay waitForSeconds:1.
Transcript showCR:'thread1 leaving critical region'.
].
]
] forkAt:5.
[
5 timesRepeat:[
Delay waitForSeconds:1.
accessLock critical:[
Transcript showCR:'thread2 in critical region'.
Delay waitForSeconds:2.
Transcript showCR:'thread2 leaving critical region'.
].
]
] forkAt:4.
|
a deadlock due to recursive enter of a critical region:
|accessLock block|
accessLock := Semaphore forMutualExclusion.
block := [:arg |
Transcript showCR:'about to enter'.
accessLock critical:[
Transcript showCR:'entered - doing action'.
arg value
].
Transcript showCR:'left region'.
].
block value:[]. 'this works'.
block value:[block value:[] ]. 'this deadlocks'.
|
Avoid the deadlock by using a RecursionLock instead:
|accessLock block|
accessLock := RecursionLock new.
block := [:arg |
Transcript showCR:'about to enter'.
accessLock critical:[
Transcript showCR:'entered - doing action'.
arg value
].
Transcript showCR:'left region'.
].
block value:[]. 'this works'.
block value:[block value:[] ]. 'this deadlocks'.
|
Wait for multiple processes to arrive at a sync-point:
|syncSema proceedSema thread1 thread2 thread3|
syncSema := Semaphore new.
syncSema setCount:(1-3).
proceedSema := Semaphore new.
thread1 := [
Transcript showCR:'here is thread 1; now busy ...'.
Delay waitForSeconds:(2 + (Random nextIntegerBetween:2 and:4)).
Transcript showCR:'here is thread 1 again - now syncing.'.
syncSema signal.
Transcript showCR:'thread 1 is waiting for all others...'.
proceedSema wait.
Transcript showCR:'thread 1 done.'.
] newProcess.
thread2 := [
Transcript showCR:'here is thread 2; now busy ...'.
Delay waitForSeconds:(3 + (Random nextIntegerBetween:2 and:4)).
Transcript showCR:'here is thread 2 again - now syncing.'.
syncSema signal.
Transcript showCR:'thread 2 is waiting for all others...'.
proceedSema wait.
Transcript showCR:'thread 2 done.'.
] newProcess.
thread3 := [
Transcript showCR:'here is thread 3; now busy ...'.
Delay waitForSeconds:(4 + (Random nextIntegerBetween:2 and:4)).
Transcript showCR:'here is thread 3 again - now syncing.'.
syncSema signal.
Transcript showCR:'thread 3 is waiting for all others...'.
proceedSema wait.
Transcript showCR:'thread 3 done.'.
] newProcess.
thread1 priority:7.
thread2 priority:6.
thread3 priority:9.
thread1 resume.
thread2 resume.
thread3 resume.
Transcript showCR:'main thread: now waiting for other threads...'.
syncSema wait.
Transcript showCR:'main thread: all other threads at syncPoint.'.
Delay waitForSeconds:2.
Transcript showCR:'main thread: now let them proceed...'.
proceedSema signalForAll.
Transcript showCR:'main thread: done.'.
|
waitWithTimeout:0 can also be used to conditionally aquire the semaphore
i.e. only aquire it if its available.
|s|
s := Semaphore new.
[
(s waitWithTimeout:0) notNil ifTrue:[
Transcript showCR:'process1 got the sema'.
Delay waitForSeconds:1.
Transcript showCR:'process1 signals sema'.
s signal.
] ifFalse:[
Transcript showCR:'process1 has NOT got the sema'.
].
] fork.
[
(s waitWithTimeout:0) notNil ifTrue:[
Transcript showCR:'process2 got the sema'.
Delay waitForSeconds:1.
Transcript showCR:'process2 signals sema'.
s signal.
] ifFalse:[
Transcript showCR:'process2 has NOT got the sema'.
]
] fork.
s signal.
Delay waitForSeconds:0.5.
Transcript showCR:'master waits for sema'.
s wait.
Transcript showCR:'master got the sema'.
|