代码之家  ›  专栏  ›  技术社区  ›  attdona

如何并行运行多个调用thread::sleep的未来?[副本]

  •  3
  • attdona  · 技术社区  · 6 年前

    我有一个缓慢的未来,在运行到完成前阻塞1秒。

    我试着用 join my_app 按顺序执行操作:

    #![feature(pin, futures_api, arbitrary_self_types)]
    
    extern crate futures; // v0.3
    
    use futures::prelude::*;
    use futures::task::Context;
    use std::pin::PinMut;
    use std::{thread, time};
    use futures::executor::ThreadPoolBuilder;
    
    struct SlowComputation {}
    
    impl Future for SlowComputation {
        type Output = ();
    
        fn poll(self: PinMut<Self>, _cx: &mut Context) -> Poll<Self::Output> {
            let millis = time::Duration::from_millis(1000);
            thread::sleep(millis);
    
            Poll::Ready(())
        }
    }
    
    fn main() {
        let fut1 = SlowComputation {};
        let fut2 = SlowComputation {};
        let my_app = fut1.join(fut2);
    
        ThreadPoolBuilder::new()
            .pool_size(5)
            .create()
            .expect("Failed to create threadpool")
            .run(my_app);
    }
    

    参加 像那样工作?我期望未来会在不同的线程上产生。

    实现目标的正确方法是什么?

    [dependencies]
    futures-preview = "0.3.0-alfa.6"
    

    结果:

    $ time target/debug/futures03
    
    real    0m2.004s
    user    0m0.000s
    sys 0m0.004s
    
    1 回复  |  直到 5 年前
        1
  •  6
  •   Shepmaster Tim Diekmann    6 年前

    如果你把未来和 join() 他们会变成一个 ,运行在 单线程 .

    如果未来行为良好,它们将以事件驱动(异步)方式并行运行。您希望应用程序休眠1秒。

    但不幸的是你的未来 举止得体。它阻塞当前线程一秒钟,不允许在此期间执行任何其他工作。因为未来在同一个线程上运行,所以它们不能同时运行。应用程序将休眠2秒。

    fn main() {
        let fut1 = SlowComputation {};
        let fut2 = SlowComputation {};
    
        let mut pool = ThreadPoolBuilder::new()
            .pool_size(5)
            .create()
            .expect("Failed to create threadpool");
    
        pool.spawn(fut1);
        pool.run(fut2);
    }
    

    写阻止主线程的未来是 高度地 tokio::timer::Delay tokio::timer::timeout::Timeout