WaitGroup

Inherits from: Object

A synchronization barrier for waiting on a group of concurrent operations.

Add a count with add:, decrement it with done, and block on wait until the count reaches zero. The convenience method wrap: combines add, fork, and done into a single call.

Example
WaitGroup new count              "=> 0"

| wg <WaitGroup> |
wg := WaitGroup new.
wg add: 3.
wg count                         "=> 3"

wg := WaitGroup new.
wg add: 1.
wg done.
wg count                         "=> 0"

wg := WaitGroup new.
wg wrap: [42].
wg wait.
wg count                         "=> 0"
Example
"Fan-out / fan-in pattern"
| results <Channel> wg <WaitGroup> |
results := Channel new: 5.
wg := WaitGroup new.
1 to: 5 do: [:i |
    wg wrap: [results send: i * 10]
].
wg wait.
results close

Class Methods

primitives

class primNew

uncategorized

class new

Create a new WaitGroup with a counter of zero.

Example
WaitGroup new count  "=> 0"

Instance Methods

primitives

primAdd:
primCount
primDone
primWait
primWrap:

uncategorized

add

Convenience method to add 1 to the counter.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg add.
wg count  "=> 1"
add:

Add count to the WaitGroup counter. Must be called before forking the corresponding work.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg add: 5.
wg count  "=> 5"
count

Return the current value of the counter.

Example
WaitGroup new count  "=> 0"
done

Decrement the counter by 1. Call this when a unit of work has finished. Panics if the counter goes below zero.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg add: 2.
wg done.
wg count  "=> 1"
forkAll:

Fork every block in blocks using wrap:, then wait for all to complete.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg forkAll: {[Process sleep: 50]. [Process sleep: 100]}
forkAllCollect:

Fork every block in blocks, wait for all to complete, and return an Array of their results in the original order.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg forkAllCollect: {[1 + 1]. [2 + 2]. [3 + 3]}
printString

Return a string describing the WaitGroup and its counter.

Example
WaitGroup new printString  "=> 'a WaitGroup (count: 0)'"
wait

Block the caller until the counter reaches zero. If the counter is already zero, returns immediately.

WARNING: Calling wait when the counter will never reach zero will deadlock.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg wrap: [Process sleep: 100].
wg wait
wrap:

Fork aBlock in a new process with automatic counter management. Increments the counter by 1 before forking and calls done when the block completes. Returns the forked Process.

Example
| wg <WaitGroup> |
wg := WaitGroup new.
wg wrap: [42].
wg wait.
wg count  "=> 0"