在Tokio中生成具有非静态生存期的任务

时间:2018-12-20 17:22:09

标签: rust lifetime rust-tokio

我有一个tokio核心,其主要任务是运行websocket(客户端)。当我从服务器收到一些消息时,我想执行一个新任务来更新一些数据。下面是一个最小的失败示例:

use tokio_core::reactor::{Core, Handle};
use futures::future::Future;
use futures::future;

struct Client {
    handle: Handle,
    data: usize,
}

impl Client {
    fn update_data(&mut self) {
        // spawn a new task that updates the data
        self.handle.spawn(future::ok(()).and_then(|x| {
            self.data += 1; // error here
            future::ok(())
        }));
    }
}

fn main() {
    let mut runtime = Core::new().unwrap();

    let mut client = Client {
        handle: runtime.handle(),
        data: 0,
    };

    let task = future::ok::<(), ()>(()).and_then(|_| {
        // under some conditions (omitted), we update the data
        client.update_data();
        future::ok::<(), ()>(())
    });
    runtime.run(task).unwrap();
}

哪个会产生此错误:

error[E0477]: the type `futures::future::and_then::AndThen<futures::future::result_::FutureResult<(), ()>, futures::future::result_::FutureResult<(), ()>, [closure@src/main.rs:13:51: 16:10 self:&mut &mut Client]>` does not fulfill the required lifetime
  --> src/main.rs:13:21                                                                                                                                                                
   |                                                                                                                                                                                   
13 |         self.handle.spawn(future::ok(()).and_then(|x| {                                                                                                                           
   |                     ^^^^^                                                                                                                                                         
   |                                                                                                                                                                                   
   = note: type must satisfy the static lifetime      

问题在于通过手柄产生的新任务需要是静态的。 here中描述了相同的问题。遗憾的是,我不清楚如何解决该问题。即使使用和ArcMutex进行了一些尝试(单线程应用程序实际上并不需要这样做),我也没有成功。

由于东京市场发展很快,我想知道目前最好的解决方案是什么。你有什么建议吗?

修改

Peter Hall的解决方案适用于以上示例。可悲的是,当我构建失败的示例时,我更换了tokio反应堆,以为它们会相似。使用tokio::runtime::current_thread

use futures::future;
use futures::future::Future;
use futures::stream::Stream;
use std::cell::Cell;
use std::rc::Rc;
use tokio::runtime::current_thread::{Builder, Handle};

struct Client {
    handle: Handle,
    data: Rc<Cell<usize>>,
}

impl Client {
    fn update_data(&mut self) {
        // spawn a new task that updates the data
        let mut data = Rc::clone(&self.data);
        self.handle.spawn(future::ok(()).and_then(move |_x| {
            data.set(data.get() + 1);
            future::ok(())
        }));
    }
}

fn main() {
    // let mut runtime = Core::new().unwrap();

    let mut runtime = Builder::new().build().unwrap();

    let mut client = Client {
        handle: runtime.handle(),
        data: Rc::new(Cell::new(1)),
    };

    let task = future::ok::<(), ()>(()).and_then(|_| {
        // under some conditions (omitted), we update the data
        client.update_data();
        future::ok::<(), ()>(())
    });
    runtime.block_on(task).unwrap();
}

我获得:

error[E0277]: `std::rc::Rc<std::cell::Cell<usize>>` cannot be sent between threads safely
--> src/main.rs:17:21                                                         
|                                                                            
17 |         self.handle.spawn(future::ok(()).and_then(move |_x| {              
|                     ^^^^^ `std::rc::Rc<std::cell::Cell<usize>>` cannot be sent between threads safely
|                                                                            
= help: within `futures::future::and_then::AndThen<futures::future::result_::FutureResult<(), ()>, futures::future::result_::FutureResult<(), ()>, [closure@src/main.rs:17:51: 20:10 data:std::rc::Rc<std::cell::Cell<usize>>]>`, the trait `std::marker::Send` is not implemented for `std::rc::Rc<std::cell::Cell<usize>>`
= note: required because it appears within the type `[closure@src/main.rs:17:51: 20:10 data:std::rc::Rc<std::cell::Cell<usize>>]`
= note: required because it appears within the type `futures::future::chain::Chain<futures::future::result_::FutureResult<(), ()>, futures::future::result_::FutureResult<(), ()>, [closure@src/main.rs:17:51: 20:10 data:std::rc::Rc<std::cell::Cell<usize>>]>`
= note: required because it appears within the type `futures::future::and_then::AndThen<futures::future::result_::FutureResult<(), ()>, futures::future::result_::FutureResult<(), ()>, [closure@src/main.rs:17:51: 20:10 data:std::rc::Rc<std::cell::Cell<usize>>]>`

因此,即使整个代码都是单线程的,在这种情况下我似乎也需要一个Arc和一个Mutex

1 个答案:

答案 0 :(得分:1)

在单线程程序中,您不需要使用ArcRc就足够了:

use std::{rc::Rc, cell::Cell};

struct Client {
    handle: Handle,
    data: Rc<Cell<usize>>,
}

impl Client {
    fn update_data(&mut self) {
        let data = Rc::clone(&self.data);
        self.handle.spawn(future::ok(()).and_then(move |_x| {
            data.set(data.get() + 1);
            future::ok(())
        }));
    }
}

要点是,您不必担心生存期,因为Rc的每个克隆的行为就像是拥有数据一样,而不是通过引用self来访问它。需要内部Cell(对于非RefCell类型则为Copy),因为Rc由于已经被克隆,因此不能被可变地取消引用。


spawn的{​​{1}}方法要求将来是tokio::runtime::current_thread::Handle,这就是导致问题更新的原因。 this Tokio Github issue中为什么会有这种解释(种类繁多)。

您可以使用Send来代替tokio::runtime::current_thread::spawn的方法,该方法将始终在当前线程中运行Future,并且 not 不需要将Future设为{{ 1}}。您可以在上面的代码中替换Handle,它将正常工作。

如果您需要在Send上使用该方法,则还需要诉诸self.handle.spawnHandle(或RwLock)来满足{{ 1}}要求:

Arc

如果您的数据确实是Mutex,则也可以使用Send而不是use std::sync::{Mutex, Arc}; struct Client { handle: Handle, data: Arc<Mutex<usize>>, } impl Client { fn update_data(&mut self) { let data = Arc::clone(&self.data); self.handle.spawn(future::ok(()).and_then(move |_x| { *data.lock().unwrap() += 1; future::ok(()) })); } } ,但我个人认为处理起来很麻烦。

相关问题