binaryninja/
worker_thread.rs

1use crate::string::IntoCStr;
2use binaryninjacore_sys::*;
3use std::ffi::c_void;
4
5pub struct WorkerThreadActionExecutor {
6    func: Box<dyn Fn()>,
7}
8
9impl WorkerThreadActionExecutor {
10    unsafe extern "C" fn cb_execute(ctx: *mut c_void) {
11        let f: Box<Self> = Box::from_raw(ctx as *mut Self);
12        f.execute();
13    }
14
15    pub fn execute(&self) {
16        (self.func)();
17    }
18}
19
20pub fn execute_on_worker_thread<F: Fn() + 'static>(name: &str, f: F) {
21    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
22    let raw_executor = Box::into_raw(boxed_executor);
23    let name = name.to_cstr();
24    unsafe {
25        BNWorkerEnqueueNamed(
26            raw_executor as *mut c_void,
27            Some(WorkerThreadActionExecutor::cb_execute),
28            name.as_ptr(),
29        )
30    }
31}
32
33pub fn execute_on_worker_thread_priority<F: Fn() + 'static>(name: &str, f: F) {
34    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
35    let raw_executor = Box::into_raw(boxed_executor);
36    let name = name.to_cstr();
37    unsafe {
38        BNWorkerPriorityEnqueueNamed(
39            raw_executor as *mut c_void,
40            Some(WorkerThreadActionExecutor::cb_execute),
41            name.as_ptr(),
42        )
43    }
44}
45
46pub fn execute_on_worker_thread_interactive<F: Fn() + 'static>(name: &str, f: F) {
47    let boxed_executor = Box::new(WorkerThreadActionExecutor { func: Box::new(f) });
48    let raw_executor = Box::into_raw(boxed_executor);
49    let name = name.to_cstr();
50    unsafe {
51        BNWorkerInteractiveEnqueueNamed(
52            raw_executor as *mut c_void,
53            Some(WorkerThreadActionExecutor::cb_execute),
54            name.as_ptr(),
55        )
56    }
57}
58
59/// Returns the number of worker threads that are currently running.
60/// By default, this is the number of cores on the system minus one
61///
62/// To set the worker thread count use [`set_worker_thread_count`].
63pub fn worker_thread_count() -> usize {
64    unsafe { BNGetWorkerThreadCount() }
65}
66
67/// Sets the number of worker threads that are currently running.
68/// By default, this is the number of cores on the system minus one.
69pub fn set_worker_thread_count(count: usize) {
70    unsafe { BNSetWorkerThreadCount(count) }
71}