pub struct Thread<T> { /* private fields */ }
Expand description
A Thread
is a simple abstraction over std::thread
that allows to offload a pure
function to a different thread (essentially emulating async / await for older compilers).
§Warning
Thread
panics if it goes out of scope before .block()
was called.
Implementations§
Source§impl<T> Thread<T>
impl<T> Thread<T>
Sourcepub fn new<U>(initial_data: U, callback: fn(_: U) -> T) -> Self
pub fn new<U>(initial_data: U, callback: fn(_: U) -> T) -> Self
Creates a new thread that spawns a certain (pure) function on a separate thread.
This is a workaround until await
is implemented. Note that invoking this function
will create an OS-level thread.
Warning: You must call .await()
, otherwise the Thread
will panic when it is dropped!
§Example
fn pure_function(input: usize) -> usize { input + 1 }
let thread_1 = Thread::new(5, pure_function);
let thread_2 = Thread::new(10, pure_function);
let thread_3 = Thread::new(20, pure_function);
// thread_1, thread_2 and thread_3 run in parallel here...
let result_1 = thread_1.block();
let result_2 = thread_2.block();
let result_3 = thread_3.block();
assert_eq!(result_1, Ok(6));
assert_eq!(result_2, Ok(11));
assert_eq!(result_3, Ok(21));
Sourcepub fn block(self) -> Result<T, BlockError>
pub fn block(self) -> Result<T, BlockError>
Block until the internal thread has finished and return T
Trait Implementations§
Auto Trait Implementations§
impl<T> Freeze for Thread<T>
impl<T> !RefUnwindSafe for Thread<T>
impl<T> Send for Thread<T>
impl<T> Sync for Thread<T>
impl<T> Unpin for Thread<T>
impl<T> !UnwindSafe for Thread<T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more