nblock
Description
nblock is a non-blocking runtime for Rust. It executes non-blocking tasks on a collection of managed threads.
Tasks
A [Task] is spawned on the [Runtime] using [Runtime::spawn].
Tasks are similar to a [std::future::Future], except that they are mutable, guaranteed to run from a single thread, and differentiate between Idle and Active states while being driven to completion.
Like a Future, a Task has an Output, which is able to be obtained using the [JoinHandle] returned by [Runtime::spawn].
Threads
Tasks are spawned onto a set of shared threads that are managed by the runtime.
A tasks is bound to a specific thread based on the provided [ThreadSelector].
Examples
Round-Robin Spawn
The following example will use a Round-Robin [ThreadSelector] to alternate runnings tasks between two threads, printing "hello, world" and the thread name for each task.
Code
use ;
use current;
let runtime = builder
.with_thread_selector
.build
.unwrap;
;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
Output
hello, world! from: "nblock thread-1"
hello, world! from: "nblock thread-2"
hello, world! from: "nblock thread-1"
hello, world! from: "nblock thread-2"
hello, world! from: "nblock thread-1"
Dedicated Spawn
The following example will use a [ThreadSelector] that spawns each task onto a dedicated thread, printing "hello, world" and the thread name for each task.
Code
use ;
use current;
let runtime = builder
.with_thread_selector
.build
.unwrap;
;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
runtime.spawn.join.unwrap;
Output
hello, world! from: "nblock task t1"
hello, world! from: "nblock task t2"
hello, world! from: "nblock task t3"
hello, world! from: "nblock task t4"
hello, world! from: "nblock task t5"
Spawn On Completion
The following example shows how to use a closure on the [JoinHandle] to automatically spawn a new task upon completion of another.
This should feel very similar to await in async code, except it is lock-free while supporting task mutability.
Also notice that within a task you may use Runtime::get() to obtain the current Runtime.
use ;
use ;
let runtime = builder
.with_thread_selector
.build
.unwrap;
runtime
.spawn
.on_complete;
sleep;
runtime
.shutdown
.unwrap;
Output
hello, world! from: "nblock thread-1"! The input was 1.
hello, world! from: "nblock thread-2"! The input was 2.
License: MIT OR Apache-2.0