Last active
January 22, 2018 12:46
-
-
Save yuk1ty/19cafce9c4a11fd748a0fe7b1c95bbc1 to your computer and use it in GitHub Desktop.
futures で直面した課題のサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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