Worker module provides abstractions for spawning and communicating with worker threads in a type-safe, platform-agnostic way. It supports bidirectional communication with automatic message handling and error propagation.
Overview
Worker features:- Type-safe message passing between main and worker threads
- Bidirectional communication (send and receive)
- Automatic error handling and propagation
- Scope-based lifecycle management
- Platform-agnostic abstractions
- Support for transferable objects
Basic Concepts
The Worker system consists of:- Spawner: Factory for creating worker instances
- Worker: Handle for communicating with a worker thread
- WorkerPlatform: Platform-specific worker implementation
- Message Protocol: Type-safe message passing
Creating Workers
Define a Spawner
First, define how workers should be spawned:Spawn a Worker
Message Passing
Sending Messages
Send messages from the main thread to the worker:Receiving Messages
Handle incoming messages in the worker usingrun:
Worker Implementation
Inside the worker file, use WorkerRunner to handle messages:Bidirectional Communication
Workers support full bidirectional message passing:Spawn Callbacks
Execute code when the worker spawns:Error Handling
Errors in workers are propagated asWorkerError:
WorkerError Types
WorkerSendError: Failed to send message to worker- Other platform-specific errors
