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
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
[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
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
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
No comments:
Post a Comment