Programmer Reference : Common Process Model : Synchronization using semaphore and delay
Synchronization using semaphore and delay
Instances of class Semaphore are used for interprocess synchronization. Semaphores can be thought of as containers for signals. (Signals are not on/off switches; multiple signals can be queued up.) Sending the message signal to a semaphore adds a signal, while sending the message wait removes a signal. If a semaphore that has no signals is sent the wait message, the process running the wait is suspended until the semaphore is sent a signal message. If more than one process is waiting on a semaphore when a signal is sent, the longest waiting process is resumed.
The following example illustrates the use of Semaphores. A process is forked at a high priority. It blocks, waiting on a Semaphore. Each time the user interface signals the Semaphore the forked process unblocks, increments a counter, and blocks on the Semaphore again. The user interface process then prints the counter value. After the example is run, the Semaphore becomes garbage, and the original process disappears with the Semaphore.
| count aSemaphore testProcess output |
output := WriteStream on: String new.
count := 1.
aSemaphore := Semaphore new.
testProcess := [
[true] whileTrue: [
aSemaphore wait.
output nextPutAll: 'Process has acquired the Semaphore. ',
'Incrementing count.'; cr.
count := count + 1.]
] forkAt: Processor timingPriority.
aSemaphore signal.
output nextPutAll: 'After First signal, count = ', count printString; cr.
aSemaphore signal.
output nextPutAll: 'After Second signal, count = ', count printString; cr.
Transcript show: output contents
 
Transcript Output:
Process has acquired the Semaphore. Incrementing count.
After First signal, count = 2
Process has acquired the Semaphore. Incrementing count.
After Second signal, count = 3
Instances of class Delay are used to effect synchronization with the real-time clock, and to postpone process execution for a specified time period. Postponement can be specified in milliseconds, seconds, or until a specific time. Each Delay has a resumption time specified in milliseconds since midnight. When the Delay is sent the wait message, the process running the wait operation is suspended until the real-time clock advances to the resumption time specified by the Delay.
To illustrate the use of Delay, evaluate the following code fragment. A message is displayed on the Transcript after about 15 seconds.
[(Delay forSeconds: 15) wait.
Transcript show: 'Executing delay example'; cr] fork.
Last modified date: 01/29/2015