Created
August 14, 2021 15:34
-
-
Save bepitulaz/a8f1ca9b6bd1f5d456f10aa2df6018eb to your computer and use it in GitHub Desktop.
Spawning 1000 threads to do concurrent HTTP call with Rust standard library.
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
// This gist is a solution from a challenge that I found in Twitter. | |
// The challenge is writing code to do 1000 HTTP GET concurently with any favourite programming languages. | |
// Here's the URL: https://twitter.com/codingfess/status/1426142985532575747 | |
use std::thread; | |
use std::io::prelude::*; | |
use std::net::{TcpStream}; | |
fn http_call(hostname: &str) { | |
let mut stream = TcpStream::connect((hostname, 80)).unwrap(); | |
let header = format!("GET /get HTTP/1.1\r\nHost: {}\r\nAccept: */*\r\nConnection: close\r\n\r\n", hostname); | |
let mut result: String = "".to_string(); | |
let response = stream.write(header.as_bytes()); | |
match response { | |
Ok(_) => { | |
// Reading HTTP response. | |
// We can print it or deserialize it later. | |
stream.read_to_string(&mut result).unwrap(); | |
}, | |
Err(e) => panic!("{}", e) | |
} | |
} | |
fn main() { | |
let hostname = "httpbin.org"; | |
let mut children_thread = vec![]; | |
for i in 0..=1000 { | |
// Spawn thread | |
children_thread.push(thread::spawn(move || { | |
http_call(hostname); | |
println!("Run request number: {}", i); | |
})); | |
} | |
for child in children_thread { | |
let _ = child.join(); | |
} | |
println!("All requests are completed."); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment