run

Function run 

Source
pub fn run<F: FnOnce() -> R, R: IntoFuture>(f: F) -> Result<R::Item, R::Error>
Expand description

Run the main loop and initialize it by running a function

This is basically a shortcut for:

let mut lp = Core::new().expect("create loop");
lp.run(futures::lazy(f))

The difference between run() and run_forever() is merely a convenience. Basically, you want to use run() in client applications when you have a future that should complete to proceed. And run_forever() in server applications which spawns some listeners and never exits.

But also initializes thread-local loop handle for the time of loop run

Examples found in repository?
examples/mininal.rs (lines 8-10)
6fn main() {
7
8    run(|| {
9        Ok::<_, io::Error>(())
10    }).unwrap();
11}
More examples
Hide additional examples
examples/timeout.rs (lines 10-17)
8fn main() {
9
10    run(|| {
11        println!("Sleeping 1 second");
12        timeout(Duration::new(1, 0))
13        .and_then(|()| {
14            println!("Done");
15            Ok(())
16        })
17    }).unwrap();
18}
examples/multi-threaded.rs (lines 23-31)
14fn main() {
15    let addr = env::args().nth(1).unwrap_or("127.0.0.1:7777".to_string());
16    let addr = addr.parse::<SocketAddr>().expect("parse address");
17
18    let socket = StdListener::bind(addr).expect("bind socket");
19    let mut threads = Vec::new();
20    for thread_no in 0..10 {
21        let lst = socket.try_clone().expect("cloning bind socket");
22        threads.push(thread::spawn(move || {
23            run(|| {
24                TcpListener::from_listener(lst, &addr, &handle())
25                .expect("listener created")
26                .incoming()
27                .for_each(|(_sock, addr)| {
28                    println!("Accepted {} in thread {}", addr, thread_no);
29                    Ok(())
30                })
31            })
32        }))
33    }
34    for t in threads {
35        t.join().expect("thread never joins").expect("accept never fails");
36    }
37}