Skip to content

Commit e2f7734

Browse files
committed
Limit the amount of parallelism in check_all
Don't create more threads than there are CPU cores.
1 parent 5c17abd commit e2f7734

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

src/app_state.rs

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::{
55
io::{self, Read, Seek, StdoutLock, Write},
66
path::{Path, MAIN_SEPARATOR_STR},
77
process::{Command, Stdio},
8-
sync::mpsc,
8+
sync::{atomic::AtomicUsize, mpsc, Arc},
99
thread,
1010
};
1111

@@ -20,6 +20,7 @@ use crate::{
2020
};
2121

2222
const STATE_FILE_NAME: &str = ".rustlings-state.txt";
23+
const DEFAULT_CHECK_PARALLELISM: usize = 8;
2324

2425
#[must_use]
2526
pub enum ExercisesProgress {
@@ -411,17 +412,31 @@ impl AppState {
411412

412413
let (mut checked_count, mut results) = thread::scope(|s| {
413414
let (tx, rx) = mpsc::channel();
414-
415-
self.exercises
416-
.iter()
417-
.enumerate()
418-
.for_each(|(index, exercise)| {
419-
let tx = tx.clone();
420-
let cmd_runner = &self.cmd_runner;
421-
let _ = thread::Builder::new().spawn_scoped(s, move || {
422-
tx.send((index, exercise.run_exercise(None, cmd_runner)))
423-
});
415+
let exercise_ind = Arc::new(AtomicUsize::default());
416+
417+
let num_core = thread::available_parallelism()
418+
.map_or(DEFAULT_CHECK_PARALLELISM, |count| count.get());
419+
(0..num_core).for_each(|_| {
420+
let tx = tx.clone();
421+
let exercise_ind = exercise_ind.clone();
422+
let this = &self;
423+
let _ = thread::Builder::new().spawn_scoped(s, move || {
424+
loop {
425+
let exercise_ind =
426+
exercise_ind.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
427+
let Some(exercise) = this.exercises.get(exercise_ind) else {
428+
// No more exercises
429+
break;
430+
};
431+
if tx
432+
.send((exercise_ind, exercise.run_exercise(None, &this.cmd_runner)))
433+
.is_err()
434+
{
435+
break;
436+
}
437+
}
424438
});
439+
});
425440

426441
// Drop this `tx`, since the `rx` loop will not stop while there is
427442
// at least one tx alive (i.e. we want the loop to block only while

0 commit comments

Comments
 (0)