Skip to content

Instantly share code, notes, and snippets.

@yuk1ty
Last active January 22, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuk1ty/19cafce9c4a11fd748a0fe7b1c95bbc1 to your computer and use it in GitHub Desktop.
Save yuk1ty/19cafce9c4a11fd748a0fe7b1c95bbc1 to your computer and use it in GitHub Desktop.
futures で直面した課題のサンプルコード
extern crate hyper;
extern crate tokio_core;
extern crate futures;
use hyper::{Client, Uri};
use tokio_core::reactor::Core;
use futures::future::Future;
// 処理のブロックが起きてしまっている例
fn main() {
let mut core = Core::new().unwrap();
let client = Client::new(&core.handle());
let uri: Uri = "http://httpbin.org/ip".parse().unwrap();
for _ in 0..10 {
let work = client.get(uri.clone()).map(|res| {
println!("Response {}", res.status())
});
// これではブロッキングしてしまって意味がない
core.run(work).unwrap();
}
}
extern crate hyper;
extern crate tokio_core;
extern crate futures;
use hyper::{Client, Uri};
use tokio_core::reactor::Core;
use futures::future::Future;
// 処理のブロックを起こさずにできそうだけど、所有権とかいろんなものに阻まれてなかなかめんどくさい例
fn main() {
let mut core = Core::new().unwrap();
let client = Client::new(&core.handle());
let uri: Uri = "http://httpbin.org/ip".parse().unwrap();
// 何かしらの方法で Future を初期化して保持
// あるいは、ここを Vec<Future> みたいな形にして、l: 27の直前で一気に畳み込みで future#join するとか?
let init = ...;
for _ in 0..10 {
// あるいは、この中で畳み込みみたいな処理を走らせるとか?
let work = client.get(uri.clone()).map(|res| {
println!("Response {}", res.status())
});
init.join(work);
}
// ここで Core#run すれば、内部で10個分の future がノンブロッキングで走る(はず)
core.run(init).unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment