thread Module

The thread module implements an Actor-Model concurrency architecture. Worker threads run isolated bytecode VM instances in parallel OS threads, communicating via message passing.

Safe, Lock-Free Parallelism

Because each worker thread operates inside its own isolated VM heap, you never have to worry about data races, mutex deadlocks, or manual memory synchronizations. Communication is handled purely through message passing.

Importing

djazair
use thread

Spawning Workers & Message Passing

djazair
use thread

# Spawn a worker executing inline Djazair code
let worker = thread.spawnCode(`
    use thread
    
    # Receive message from parent thread
    let message = thread.receive()
    print("Worker received: " + message)
    
    # Reply back to parent
    thread.reply("Processed: " + message.upper())
`)

# Send message to worker
worker.send("djazair concurrency")

# Receive reply with a 2-second timeout
let response = worker.receive(2.0)
print("Parent received: ${response}")
# => Parent received: Processed: DJAZAIR CONCURRENCY

worker.join()
worker.close()

Structured JSON Messaging

Workers can exchange structured dictionaries using sendJson() and receiveJson():

djazair
use thread

let mathWorker = thread.spawnCode(`
    use thread
    let data = thread.receiveJson()
    let result = data["x"] * data["y"]
    thread.replyJson({"answer": result, "status": "ok"})
`)

mathWorker.sendJson({"x": 12, "y": 8})
let res = mathWorker.receiveJson(3.0)
print("Computed answer: ${res["answer"]}") # => 96
mathWorker.close()