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()
Thread Pools & Futures
For distributing workloads, the thread module provides built-in worker pools. Pools manage a fixed set of persistent workers and distribute tasks efficiently via a FIFO queue.
djazair
use thread
use json
# Create a pool of 4 workers using inline code
let pool = thread.inlinePool(`
use thread
use json
while True
let msg = thread.receive()
if isNull(msg) break end # Queue closed
let envelope = json.decode(msg)
if isNull(envelope) break end
let task_id = envelope["id"]
let payload = envelope["data"]
# Reply with the same task ID
thread.replyJson({"id": task_id, "data": payload * 2})
end
`, 4)
# Submit an array of tasks (returns an Array of Futures)
let futures = pool.submit([10, 20, 30])
# Wait for all tasks to complete (blocking)
let results = thread.all(futures, 5.0) # 5 seconds timeout
print(results) # => [20, 40, 60]
# Or wait for the FIRST task to complete (returns the value directly)
let fastest_value = thread.any(futures, 5.0)
print("Fastest task returned: " + str(fastest_value))
pool.close()