Skip to content

Commit

Permalink
feat(server): use an environment variable for configuring the thread
Browse files Browse the repository at this point in the history
pool size while falling back to num_cpus if it is not present
  • Loading branch information
gsquire committed Oct 19, 2017
1 parent e784b0f commit 5955b73
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ travis-ci = { repository = "steveklabnik/simple-server" }
http = "0.1.0"
httparse = "1.2.3"
log = "0.3"
num_cpus = "1"
scoped_threadpool = "0.1.7"

[dev-dependencies]
Expand Down
21 changes: 20 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ extern crate log;

extern crate http;
extern crate httparse;
extern crate num_cpus;
extern crate scoped_threadpool;

pub use http::Request;
Expand All @@ -38,6 +39,7 @@ pub use http::response::Builder as ResponseBuilder;

use scoped_threadpool::Pool;

use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream};
Expand Down Expand Up @@ -117,7 +119,8 @@ impl Server {
/// }
/// ```
pub fn listen(&self, host: &str, port: &str) {
let mut pool = Pool::new(4);
let num_threads = self.pool_size();
let mut pool = Pool::new(num_threads);
let listener =
TcpListener::bind(format!("{}:{}", host, port)).expect("Error starting the server.");

Expand All @@ -136,6 +139,22 @@ impl Server {
}
}

// Try and fetch the environment variable NUM_THREADS and parse it as a u32. If this fails
// we fall back to using the num_cpus crate.
fn pool_size(&self) -> u32 {
const NUM_THREADS: &str = "SIMPLESERVER_THREADS";
let logical_cores = num_cpus::get() as u32;

match env::var(NUM_THREADS) {
Ok(v) => {
v.parse::<u32>().unwrap_or(logical_cores)
}
Err(_) => {
logical_cores
}
}
}

fn handle_connection(&self, mut stream: TcpStream) -> Result<(), Error> {
let mut buffer = [0; 512];

Expand Down

0 comments on commit 5955b73

Please sign in to comment.