Skip to main content

Thread Library Reference

The thread library in EasyBite provides a simple, safe API for concurrent execution. While EasyBite scripts run single‑threaded by default to avoid race conditions, many real‑world tasks—such as I/O‑bound operations, heavy computations, or background work—benefit from parallelism. With thread, you can:

  • run(funcName): Spawn a native OS thread to execute a named EasyBite function.
  • join(handle): Wait for a spawned thread to finish and retrieve its return value.
  • sleep(ms): Pause the current thread for a given number of milliseconds.

All thread operations return EasyBite Result types wrapped in Value, so errors in thread creation, panics inside a thread, or double‑joins are captured and reported rather than crashing the interpreter. The thread library hides platform differences and integrates cleanly with EasyBite’s error‑handling model.


FunctionParametersDescription
run(funcName)funcName (Function)Spawn a new thread to execute the named function. Returns a ThreadHandle.
join(handle)handle (ThreadHandle)Block until the thread represented by handle completes; returns its Value.
sleep(ms)ms (Number)Pause the current thread for ms milliseconds.

Detailed Examples

1. Spawning and Joining a Thread

import thread

function computeAnswer()
return 42
end function

set handle to thread.run(computeAnswer)

// ... main script continues here ...

set result to thread.join(handle)
show(result)

Output:

42

2. Pausing Inside a Thread with sleep(ms)

import thread

function sleeper()
thread.sleep(500)
return "slept 500ms"
end function

set handle to thread.run(sleeper)
set msg to thread.join(handle)
show(msg)

Output:

"slept 500ms"

3. Parallel Computation Example

import thread

function sum1to1000()
set total to 0
for i from 1 to 1000
set total to total + i
end for
return total
end function

function factorial10()
set product to 1
for i from 1 to 10
set product to product * i
end for
return product
end function

set h1 to thread.run(sum1to1000)
set h2 to thread.run(factorial10)

show("Parallel tasks started")

set r1 to thread.join(h1)
set r2 to thread.join(h2)

show(r1) // 500500
show(r2) // 3628800

Conclusion

The thread library empowers EasyBite scripts to leverage multicore hardware and perform background tasks without blocking the main flow. By spawning threads with run, synchronizing results with join, and controlling timing with sleep, you can write responsive, concurrent code while preserving EasyBite’s safety and simplicity. Always join every thread you spawn to collect results and handle errors, avoiding orphaned threads and ensuring robust scripts.