Doug
Doug

Reputation: 35186

How do you use an executor to resolve a Future in rust?

This code panics:

extern crate futures;

use futures::Future;
use futures::future;
use futures::sync::oneshot::{channel, Canceled};
use std::thread;
use std::time::Duration;

fn maybe_oneday() -> Box<Future<Item = i32, Error = Canceled>> {
    let (s, r) = channel::<i32>();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(100));
        let _ = s.send(100);
    });
    return Box::new(r);
}

fn main() {
    let foo = maybe_oneday();
    let mut wrapper = foo.then(|x| {
        match x {
            Ok(v) => {
                println!("GOT: {:?}", v);
                future::ok::<i32, Canceled>(v)
            },
            Err(y) => {
                println!("Err: {:?}", y);
               future::err::<i32, Canceled>(y)
            }
        }
    });

    // wrapper.wait() <-- Works, but blocks
    let _ = wrapper.poll(); // <-- Panics
}

With:

thread 'main' panicked at 'no Task is currently running', /checkout/src/libcore/option.rs:891:5

Presumably I have to use some kind of executor to delegate the task resolution to; but how?

The documentation refers to my_executor, but there appear to be no implementations of this trait, and the find out more about executors link is broken?

Where do I get an executor from?

Upvotes: 1

Views: 3091

Answers (1)

Doug
Doug

Reputation: 35186

In general, tokio and futures are designed as async primitives, not as a generic task system.

Which is to say, if you have multiple tasks you wish to dispatch asynchronously and 'fire and forget' them, use thread::spawn.

If you have multiple tasks you want to run in a single thread, then Future is the right primitive to use to block in that thread until a chain of futures are resolved.

In this case, my question didn't really make sense, because I thought that Future was supposed to represent something akin to Task in C#; that is, a dynamic dispatch to a threadpool for a task to be executes later, and the potential to chain actions to happen when that tasks resolved; with those tasks in turn to be executed in, potentially, different threads.

This is not the model that futures and tokio support.

However, I add here, just to irritate the nay-sayers, the answer to the actual question I asked:

The answer is that tokio implements a number of basic Executor's, including one for arbitrary tasks.

see: https://docs.rs/tokio/0.1.1/tokio/executor/current_thread/struct.TaskExecutor.html

specifically: https://docs.rs/tokio/0.1.1/tokio/executor/current_thread/index.html

You can use them like this:

extern crate futures;
extern crate tokio;

use futures::Future;
use futures::future;
use futures::future::Executor;
use tokio::executor::current_thread;
use futures::sync::oneshot::{channel, Canceled};
use tokio::executor::current_thread::task_executor;
use std::thread;
use std::time::Duration;
use std::sync::mpsc::Sender;
use std::sync::mpsc;
use std::sync::{Arc, Mutex};

struct RemoteReactor {
    channel: Sender<Box<Future<Item=(), Error=()> + Send + 'static>>
}

impl RemoteReactor {
    fn new() -> RemoteReactor {
        let (send, recv) = mpsc::channel::<Box<Future<Item=(), Error=()> + Send + 'static>>();
        let threadsafe_recv = Arc::new(Mutex::new(recv));
        thread::spawn(move || {
            let reader = threadsafe_recv.lock().unwrap();
            current_thread::run(|_| {
                loop {
                    let future = reader.recv().unwrap();
                    println!("Got a future!");
                    task_executor().execute(future).unwrap();
                    break;
                }
            });
        });
        return RemoteReactor {
            channel: send
        };
    }

    fn execute(&self, future: Box<Future<Item=(), Error=()> + Send + 'static>) {
        self.channel.send(future).unwrap();
    }
}

fn maybe_oneday() -> Box<Future<Item=i32, Error=Canceled> + Send + 'static> {
    let (s, r) = channel::<i32>();
    thread::spawn(move || {
        thread::sleep(Duration::from_millis(100));
        let _ = s.send(100);
    });
    return Box::new(r);
}

fn main() {
    let foo = maybe_oneday();
    let wrapper = Box::new(foo.then(|x| {
        match x {
            Ok(v) => {
                println!("GOT: {:?}", v);
                future::ok::<(), ()>(())
            }
            Err(y) => {
                println!("Err: {:?}", y);
                future::err::<(), ()>(())
            }
        }
    }));

    let reactor = RemoteReactor::new();
    reactor.execute(wrapper);

    println!("Waiting for future to resolve");
    thread::sleep(Duration::from_millis(200));

    println!("All futures are probably resolved now");
}

NB. This code doesn't run on play.rust-lang.org (error[E0463]: can't find crate for tokio) for reasons I don't understand, but it does run rust 1.24:

rustc 1.24.0 (4d90ac38c 2018-02-12)

$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.1 secs
     Running `target\debug\hello_future.exe`
Waiting for future to resolve
Got a future!
GOT: 100
All futures are probably resolved now

Upvotes: 3

Related Questions