Function may::coroutine::spawn

source ·
pub unsafe fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static,
Expand description

Spawns a new coroutine, returning a JoinHandle for it.

The join handle will implicitly detach the child coroutine upon being dropped. In this case, the child coroutine may outlive the parent. Additionally, the join handle provides a join method that can be used to join the child coroutine. If the child coroutine panics, join will return an Err containing the argument given to panic.

This will create a coroutine using default parameters of Builder, if you want to specify the stack size or the name of the coroutine, use this API instead.

This API has the same semantic as the std::thread::spawn API, except that it is an unsafe method.

§Safety

  • Access TLS in coroutine may trigger undefined behavior.
  • If the coroutine exceed the stack during execution, this would trigger memory segment fault

If you find it annoying to wrap every thing in the unsafe block, you can use the go! macro instead.

§Examples

Creating a coroutine.

use may::coroutine;

let handler = unsafe {
    coroutine::spawn(|| {
        // coroutine code
    })
};

handler.join().unwrap();