Sunday, January 07, 2024

Rust: Using Windows thread pool

Rust: Using Windows thread pool

Quick demo how to use Windows thread pool in Rust using windows crate.

Create new project

PS C:\> mkdir prj
PS C:\> cd prj
PS C:\> cargo new thread_pool_work

Edit Cargo.toml like below

[package]
name = "thread_pool_work"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies.windows]
version = "0.58"
features = [
"Win32_Foundation",
"Win32_System_Threading",
]

Update src/main.rs

use windows::{core::Result, Win32::System::Threading::*};
static COUNTER: std::sync::RwLock<i32> = std::sync::RwLock::new(0);
fn main() -> Result<()>{
unsafe {
let work = CreateThreadpoolWork(Some(callback), None, None)?;
for _ in 0..10 {
SubmitThreadpoolWork(work);
}
WaitForThreadpoolWorkCallbacks(work, false);
}
let counter = COUNTER.read().unwrap();
println!("counter: {}", *counter);
Ok(())
}
extern "system" fn callback(_: PTP_CALLBACK_INSTANCE, _: *mut std::ffi::c_void, _: PTP_WORK) {
let mut counter = COUNTER.write().unwrap();
*counter += 1;
}

Run thread_pool_work

PS C:\prj\thread_pool_work> cargo run
   Compiling thread_pool_work v0.1.0 (C:\prj\thread_pool_work)
    Finished dev [unoptimized + debuginfo] target(s) in 0.64s
     Running `target\debug\thread_pool_work.exe`
counter: 10
Tags: Rust, Windows, thread pool

No comments:

How to configure nfs server on QNX 7.1

How to configure nfs server on QNX 7.1 Target: QNX 7.1 running on a VM (VMware Workstation or VirtualBox). It is assummed that the targets ...