Skip to content

Commit 7a30133

Browse files
authored
feat: add set_threads convenience method (#37)
Expose a `set_threads` convenience method on `Model` that takes a `NonZeroU32`, following the existing `make_quiet()` pattern. You can already do this with `set_option("threads", 4)`, but the typed method makes it discoverable via IDE autocomplete and catches mistakes at compile time (eg. wrong type, zero value).
1 parent 6de4748 commit 7a30133

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/lib.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
111111
use std::convert::{TryFrom, TryInto};
112112
use std::ffi::{c_void, CString};
113-
use std::num::TryFromIntError;
113+
use std::num::{NonZeroU32, TryFromIntError};
114114
use std::ops::{Bound, Index, RangeBounds};
115115
use std::os::raw::c_int;
116116
use std::ptr::null;
@@ -391,6 +391,19 @@ impl Model {
391391
self.highs.set_option(option, value)
392392
}
393393

394+
/// Set the number of threads to use when solving the model.
395+
///
396+
/// ```
397+
/// # use highs::ColProblem;
398+
/// # use highs::Sense::Maximise;
399+
/// # use std::num::NonZeroU32;
400+
/// let mut model = ColProblem::default().optimise(Maximise);
401+
/// model.set_threads(NonZeroU32::new(1).unwrap());
402+
/// ```
403+
pub fn set_threads(&mut self, threads: NonZeroU32) {
404+
self.set_option("threads", threads.get() as i32);
405+
}
406+
394407
/// Find the optimal value for the problem, panic if the problem is incoherent
395408
pub fn solve(self) -> SolvedModel {
396409
self.try_solve().expect("HiGHS error: invalid problem")
@@ -1042,4 +1055,22 @@ mod test {
10421055
let solved = model.solve();
10431056
assert_eq!(solved.objective_value(), 1.0);
10441057
}
1058+
1059+
#[test]
1060+
fn test_set_threads() {
1061+
// Verify that the option is accepted by the solver by reading it back
1062+
// via the raw C API after setting it.
1063+
use std::num::NonZeroU32;
1064+
let mut model = Model::new(RowProblem::default());
1065+
model.set_threads(NonZeroU32::new(2).unwrap());
1066+
let mut value: i32 = 0;
1067+
let option = std::ffi::CString::new("threads").unwrap();
1068+
let status = unsafe {
1069+
highs_sys::Highs_getIntOptionValue(model.as_mut_ptr(), option.as_ptr(), &mut value)
1070+
};
1071+
assert_eq!(status, highs_sys::STATUS_OK);
1072+
assert_eq!(value, 2);
1073+
}
1074+
1075+
10451076
}

0 commit comments

Comments
 (0)