Concurrency: do, await, sleep
Harneet provides a simple, readable concurrency model inspired by Go’s goroutines and modern async/await syntax:
- do spawns work concurrently and returns immediately with a Task handle.
- await(task) blocks until the Task completes and returns the function’s result.
- sleep(ms) suspends the current task for the given milliseconds.
Under the hood, a do expression runs your call in a lightweight task and returns a Task object you can await later.
Quick start
What happens: - do work(...) starts immediately and returns a Task handle without waiting. - await(task) waits for completion and yields the underlying return value. - sleep(ms) pauses the running task only.
API reference
- do
→ Task - Starts the call concurrently and returns a
Taskhandle. -
Example:
var t = do fetch(url) -
await(task: Task) → any
- Waits for the task to finish and returns the call’s result (or
None). -
Example:
var data = await(t) -
sleep(ms: int) → None
- Suspends the current task for
msmilliseconds (must be non-negative). - Example:
sleep(100)
Notes: - Errors are returned by your function in the normal way (e.g., tuples (value, error)), and await() simply yields that same return value. There is no separate “rejection” channel. - Task inspection prints whether a task is pending or done with its result.
Patterns
1) Fan-out / fan-in
Spawn many tasks, then gather results:
2) Parallel map helper
| Parallel Map Helper | |
|---|---|
3) Handling errors with tuples
If your function returns (value, error), just await and handle the tuple:
| Handling Errors with Tuples | |
|---|---|
4) Staggered completion
Tasks can complete in any order; await determines when you observe results:
| Staggered Completion | |
|---|---|
Scheduler API
Harneet includes a small, developer-friendly scheduler API for orchestrating tasks and handling timeouts and cancellation. It is designed to be type-safe and never swallow errors.
Overview
- TaskGroup: group and operate on multiple tasks together
- Methods:
add(task),addAll(array),awaitAll() -> array,awaitAny() -> (index int, result any),len() -> int,clear(),tasks() -> array - Timeouts:
awaitWithTimeout(task, ms) -> (result any, error) - Cancellation: cooperative token primitives
newCancelToken() -> CancelTokencancel(token)isCancelled(token) -> boolsleepUntil(ms, token) -> (None, error)
Examples
Design notes
- Concurrency is implemented via lightweight tasks;
dois analogous to spawning a goroutine. await()acts like a join on a single task and returns the task’s result.sleep()blocks only the current task, not the whole program.- Built-in timeouts and cancellation are available:
awaitWithTimeout(task, ms)produces(result, error)and never swallows errors.newCancelToken()+cancel()enable cooperative cancellation; pair withsleepUntil(ms, token).
See also
- Example file:
examples/concurrency/do_await_sleep_test.ha - Control flow:
site/docs/general/control_flow.md