【问题标题】:Why does this example iron code seem to block?为什么这个示例铁代码似乎阻塞?
【发布时间】:2015-11-03 06:28:32
【问题描述】:

我正在从http://ironframework.io 主页运行这个 hello world 示例代码:

extern crate iron;

use iron::prelude::*;
use iron::status;

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    }

    Iron::new(hello_world).http("localhost:3000").unwrap();
    println!("On 3000");
}

我预计会在标准输出上看到“On 3000”,但它从未出现。我的猜测是主线程在执行 println 之前被阻塞了。为什么会这样?

如果我使用一个临时的并在之后调用 unwrap,我会得到预期的输出:

fn main() {
    fn hello_world(_: &mut Request) -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    }

    let result = Iron::new(hello_world).http("localhost:3000");
    println!("On 3000");
    result.unwrap();
}

为什么在返回值上调用 unwrap 时行为会发生变化?

我正在运行 Rust 1.1.0 和 Iron 0.1.20。

【问题讨论】:

    标签: rust iron


    【解决方案1】:

    在我写完这个问题后,我想到了答案。

    http 函数返回一个HttpResult&lt;Listening&gt; Listening 类型有一个析构函数,它在线程上调用 join,从而阻塞。

    在第一种情况下,返回对象的生命周期在 unwrap 调用之后完成,因此调用了加入线程的析构函数。如果我将它分配给一个变量,则在调用 unwrap 之前不会调用析构函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      • 2017-07-14
      相关资源
      最近更新 更多