Tracks
/
Factor
Factor
/
Exercises
/
Quayside Crew
Quayside Crew

Quayside Crew

Learning Exercise

Introduction

Factor's threads are cooperative coroutines — they share one OS thread, hand control to each other at I/O and at explicit yield points, and never run truly simultaneously. Anything you do between yields happens as one uninterrupted step. But if a compound operation (read-modify-write) yields midway, another thread can slip in and change the world before you finish — and that's a race.

This exercise covers four primitives that come up over and over:

parallel-map — fork/join over a sequence

parallel-map ( seq quot: ( elt -- newelt ) -- newseq )

In concurrency.combinators. Spawns one thread per element, runs the quotation, and collects the results back into a new sequence in the same order:

USING: concurrency.combinators sequences ;

{ "alpha" "beta" "gamma" } [ length ] parallel-map .
! => { 5 4 5 }

spawn — start a thread

spawn ( quot name -- thread )

In threads. The quotation runs concurrently; name is a label for debugging. The returned thread handle is mostly uninteresting at this level — drop it.

Promises — single-shot value handoff

<promise>           ( -- promise )
fulfill             ( value promise -- )
?promise            ( promise -- value )

In concurrency.promises. A promise is a one-shot mailbox: one thread fulfils it, others read it. ?promise blocks until the promise has been fulfilled, then returns the value.

USING: concurrency.promises kernel threads ;

<promise> [
    [ 42 swap fulfill ] curry "answer" spawn drop
] keep ?promise .
! => 42

spawn + <promise> is what parallel-map is built from; hand-rolling them is useful when each task does something other than "compute one element."

The typical fan-out/join shape over a sequence is: for each input make a fresh promise, spawn a thread that does the work and fulfills the promise, collect every promise into a sequence, then ?promise each one to wait for completion. Locals make this readable — bind the promise to a name with :> inside a [| | ] lambda so the spawned quotation can close over it:

! DOCTEST: SKIP   (`:>` only works inside [let, [|, or :: forms)
inputs [| x |
    <promise> :> p
    [ x do-work t p fulfill ] "worker" spawn drop
    p
] map [ ?promise drop ] each

Locks — mutual exclusion

<lock>     ( -- lock )
with-lock  ( lock quot -- )

In concurrency.locks. Only one thread can hold a given lock at a time. with-lock acquires, runs the quotation, releases — even if the quotation throws.

! DOCTEST: SKIP   (`:>` only works inside [let, [|, or :: forms)
USING: concurrency.locks kernel locals ;

[let <lock> :> guard
    guard [ ! exclusive section ! ] with-lock
]

Use a lock whenever a value is read or written by more than one thread and the operations on it aren't naturally atomic. Both reads and writes need the lock — a read that yields midway can see torn state.

Instructions

It's the night shift down at Hull's quayside. The freighter Olwen is moored alongside, and a crew of dockhands works the manifest in parallel. Every crate must be weighed before it goes aboard, and the harbour master keeps a single running tonnage tally that every hoist updates. The catch: there is only one quayside crane, so the tally cannot be torn by two dockhands updating it at the same time.

Each crate is an array of item weights. Crate weight is the sum of those items.

1. Weigh a crate

Define weigh-crate to take a crate and return its total weight. This is plain sequential work — one crate, one number out.

{ 12 8 15 } weigh-crate .
! => 35

2. Weigh the whole manifest in parallel

Define weigh-all to take an array of crates and return the array of their weights, in the same order. Use parallel-map so the per-crate work happens concurrently.

{ { 5 5 } { 10 } { 3 4 5 } } weigh-all .
! => { 10 10 12 }

3. Build a fresh crane

Define <crane> to construct a new crane: a tuple with a fresh <lock> and a tonnage of 0. The crane is the shared resource that subsequent tasks will protect.

<crane> tonnage>> .
! => 0

4. Hoist a crate onto the running tally

Define hoist-crate to take a weight and a crane and add the weight to the crane's tonnage under the crane's lock, so the read-add-write is atomic against other dockhands hoisting at the same time.

<crane>
35 over hoist-crate
17 over hoist-crate
tonnage>> .
! => 52

5. Read the running tonnage

Define crane-tonnage to return the crane's current tonnage — also under the lock, so the read can't see a torn value mid- hoist.

<crane>
35 over hoist-crate
crane-tonnage .
! => 35

6. Load the cargo

Define load-cargo to take an array of crates and a crane, and for each crate, spawn a dockhand thread that weighs the crate and hoists the weight onto the crane. The word returns only once every dockhand has finished. Use <promise> and ?promise to coordinate the join.

<crane> :> crane
{ { 5 5 } { 10 } { 3 4 5 } } crane load-cargo
crane crane-tonnage .
! => 32
Edit via GitHub The link opens in a new window or tab
Factor Exercism

Ready to start Quayside Crew?

Sign up to Exercism to learn and master Factor with 47 concepts163 exercises, and real human mentoring, all for free.