Guides · 04

Build a Concurrent Task Processor

Build a parallel fan-out / fan-in job processor using spawn, join, typed Channel<T>, and clock() timing in Ochre.

In this guide you will build a concurrent batch processor that fans out independent jobs across parallel tasks using spawn, streams progress events over a typed Channel<Str>, and aggregates typed results with join.

Architecture

  1. A shared Channel<Str> collects status messages from all workers.
  2. Each worker is launched with spawn { ... } and returns a typed Int result (Task<Int>).
  3. A coordinator task joins all workers and closes the channel once every worker completes.
  4. main() drains the channel until recv(ch) returns None, then prints total elapsed time using clock().

Complete Implementation (processor.och)

fn heavy_work(job_id: Int, rounds: Int) -> Int {
    var acc = 0
    for i in 1..rounds {
        acc += (i * job_id) % 97
    }
    return acc
}

fn main() {
    let t0 = clock()
    let events: Channel<Str> = channel()

    let w1 = spawn {
        let res = heavy_work(1, 5000)
        send(events, "worker-1 finished: {res}")
        return res
    }

    let w2 = spawn {
        let res = heavy_work(2, 5000)
        send(events, "worker-2 finished: {res}")
        return res
    }

    let w3 = spawn {
        let res = heavy_work(3, 5000)
        send(events, "worker-3 finished: {res}")
        return res
    }

    let summary_task = spawn {
        let total = join(w1) + join(w2) + join(w3)
        close(events)
        return total
    }

    var active = true
    while active {
        match recv(events) {
            Some(line) => println("[event] {line}"),
            None => {
                active = false
            },
        }
    }

    let grand_total: Int = join(summary_task)
    let elapsed = clock() - t0
    println("grand_total={grand_total}, elapsed={elapsed}s")
}

Running the Processor

ochre processor.och

Example Output

[event] worker-2 finished: 239900
[event] worker-1 finished: 239952
[event] worker-3 finished: 239850
grand_total=719702, elapsed=0.014s

Notice that workers execute in parallel on OS threads, so event order reflects real concurrent completion, while join(summary_task) guarantees deterministic aggregation.