Skip to content

Commit

Permalink
Add ability to pin threads
Browse files Browse the repository at this point in the history
  • Loading branch information
Faizaan Pervaiz committed Dec 12, 2023
1 parent 0a2489c commit 27680cc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
3 changes: 2 additions & 1 deletion spdlog/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,14 @@ release-level-trace = []
source-location = []
native = []
libsystemd = ["libsystemd-sys"]
multi-thread = ["crossbeam"]
multi-thread = ["crossbeam", "core_affinity"]

[dependencies]
arc-swap = "1.5.1"
atomic = "0.5.1"
cfg-if = "1.0.0"
chrono = "0.4.22"
core_affinity = { version = "0.8.1", optional = true }
crossbeam = { version = "0.8.2", optional = true }
flexible-string = { version = "0.1.0", optional = true }
if_chain = "1.0.2"
Expand Down
23 changes: 22 additions & 1 deletion spdlog/src/thread_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ pub struct ThreadPool {
pub struct ThreadPoolBuilder {
capacity: usize,
threads: usize,
core_id: Option<usize>,
}

struct Worker {
Expand All @@ -53,6 +54,7 @@ impl ThreadPool {
ThreadPoolBuilder {
capacity: 8192,
threads: 1,
core_id: None,
}
}

Expand Down Expand Up @@ -117,7 +119,17 @@ impl ThreadPoolBuilder {
self
}

/// Specify the core ID to which the thread pool should be pinned when built. Only one thread
/// will be pinned to the specified core as the thread pool currently only has one thread.
pub fn affinity(&mut self, core_id: usize) -> &mut Self {
self.core_id = Some(core_id);
self
}

/// Builds a [`ThreadPool`].
///
/// # Panics
/// Panics if core affinity has been set using [`ThreadPoolBuilder::affinity`] and pinning the thread to that core failed.
pub fn build(&self) -> Result<ThreadPool> {
if self.capacity < 1 {
return Err(Error::InvalidArgument(
Expand All @@ -136,7 +148,16 @@ impl ThreadPoolBuilder {
let mut threads = Vec::new();
threads.resize_with(self.threads, || {
let receiver = receiver.clone();
Some(thread::spawn(move || Worker { receiver }.run()))
let core_id = self.core_id;

Some(thread::spawn(move || {
if let Some(core_id) = core_id {
if !core_affinity::set_for_current(core_affinity::CoreId { id: core_id }) {
panic!("failed to pin thread to core {}", core_id);
}
}
Worker { receiver }.run()
}))
});

Ok(ThreadPool {
Expand Down

0 comments on commit 27680cc

Please sign in to comment.