From c366649516dcd1d780ca8b7938397dac61338c15 Mon Sep 17 00:00:00 2001 From: Rob Ede Date: Fri, 7 Jun 2024 16:57:03 +0100 Subject: [PATCH] docs: example of CPU core pinning --- actix-web/Cargo.toml | 2 +- actix-web/examples/worker-cpu-pin.rs | 41 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 actix-web/examples/worker-cpu-pin.rs diff --git a/actix-web/Cargo.toml b/actix-web/Cargo.toml index 9f3ab6e5e..a666f14be 100644 --- a/actix-web/Cargo.toml +++ b/actix-web/Cargo.toml @@ -35,7 +35,6 @@ features = [ "secure-cookies", ] - [lib] name = "actix_web" path = "src/lib.rs" @@ -130,6 +129,7 @@ awc = { version = "3", features = ["openssl"] } brotli = "6" const-str = "0.5" +core_affinity = "0.8" criterion = { version = "0.5", features = ["html_reports"] } env_logger = "0.11" flate2 = "1.0.13" diff --git a/actix-web/examples/worker-cpu-pin.rs b/actix-web/examples/worker-cpu-pin.rs new file mode 100644 index 000000000..58e060821 --- /dev/null +++ b/actix-web/examples/worker-cpu-pin.rs @@ -0,0 +1,41 @@ +use std::{ + io, + sync::{ + atomic::{AtomicUsize, Ordering}, + Arc, + }, + thread, +}; + +use actix_web::{middleware, web, App, HttpServer}; + +async fn hello() -> &'static str { + "Hello world!" +} + +#[actix_web::main] +async fn main() -> io::Result<()> { + env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); + + let core_ids = core_affinity::get_core_ids().unwrap(); + let n_core_ids = core_ids.len(); + let next_core_id = Arc::new(AtomicUsize::new(0)); + + HttpServer::new(move || { + let pin = Arc::clone(&next_core_id).fetch_add(1, Ordering::AcqRel); + log::info!( + "setting CPU affinity for worker {}: pinning to core {}", + thread::current().name().unwrap(), + pin, + ); + core_affinity::set_for_current(core_ids[pin]); + + App::new() + .wrap(middleware::Logger::default()) + .service(web::resource("/").get(hello)) + }) + .bind(("127.0.0.1", 8080))? + .workers(n_core_ids) + .run() + .await +}