Function pawawwewism::background

source ·
pub fn background<R, F>(f: F) -> Background<R>where
    R: Send + Sync + 'static,
    F: FnOnce() -> R + Send + 'static,
Expand description

Spawns a run-to-completion Background thread.

Examples

Get a pair of connected TcpStreams by connecting to a TcpListener in a background thread:

use pawawwewism::background;
use std::net::{TcpListener, TcpStream, Ipv4Addr};

let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
let port = listener.local_addr().unwrap().port();

let client = background(move || TcpStream::connect((Ipv4Addr::LOCALHOST, port)));
let (server, _) = listener.accept().unwrap();
let client = client.join().unwrap();

Both TcpStream::connect and TcpListener::accept block the caller, so this is not possible in a single thread without using async.