Cookbook: Parallel Worker Pool

Distribute heavy computations across multiple CPU cores using actor worker threads and asynchronous JSON messaging.

Worker Pool Implementation

djazair
use thread
use os

let numWorkers = os.cpuCount()
print("Starting ${numWorkers} parallel workers...")

let workers = []
for i in 0..numWorkers - 1
    let w = thread.spawnCode(`
        use thread
        use math
        
        while True
            let task = thread.receiveJson()
            if task == Null or task["cmd"] == "stop" break end
            
            # Heavy calculation (e.g. factorial)
            let result = math.factorial(int(task["n"]))
            thread.replyJson({"id": task["id"], "result": result})
        end
    `)
    workers.append(w)
end

# Distribute tasks
for i in 1..numWorkers
    let target = workers[i - 1]
    target.sendJson({"id": i, "n": i * 5, "cmd": "work"})
end

# Collect answers
for w in workers
    let reply = w.receiveJson(5.0)
    print("Task #${reply["id"]} calculated: ${reply["result"]}")
    w.sendJson({"cmd": "stop"})
    w.close()
end