Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tracing warning when a thread blocks steps #162

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions src/sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::cell::RefCell;
use std::future::Future;
use std::net::IpAddr;
use std::ops::DerefMut;
use std::sync::Arc;
use std::sync::mpsc::RecvTimeoutError;
use std::sync::{Arc, mpsc};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::Relaxed;
use std::time::UNIX_EPOCH;

use indexmap::IndexMap;
Expand Down Expand Up @@ -32,7 +35,7 @@ pub struct Sim<'a> {
/// Simulation elapsed time
elapsed: Duration,

steps: usize,
steps: Arc<AtomicUsize>,
}

impl<'a> Sim<'a> {
Expand All @@ -48,7 +51,7 @@ impl<'a> Sim<'a> {
rts: IndexMap::new(),
since_epoch,
elapsed: Duration::ZERO,
steps: 1, // bumped after each step
steps: Arc::new(1.into()), // bumped after each step
}
}

Expand Down Expand Up @@ -315,6 +318,27 @@ impl<'a> Sim<'a> {
/// Executes a simple event loop that calls [step](#method.step) each iteration,
/// returning early if any host software errors.
pub fn run(&mut self) -> Result {
let steps = self.steps.clone();
let (_tx, rx) = mpsc::channel::<()>();
std::thread::spawn(move || {
let mut blocked = false;
loop {
let prev = steps.load(std::sync::atomic::Ordering::Relaxed);
// Exit if main thread has.
match rx.recv_timeout(Duration::from_secs(10)) {
Ok(_) | Err(RecvTimeoutError::Disconnected) => break,
_ => {}
}
if steps.load(std::sync::atomic::Ordering::Relaxed) == prev {
if !blocked {
tracing::warn!("A task is blocking preventing simulation steps at step {}.", prev);
}
blocked = true;
} else {
blocked = false;
}
}
});
loop {
let is_finished = self.step()?;

Expand All @@ -334,7 +358,7 @@ impl<'a> Sim<'a> {
///
/// Returns whether or not all clients have completed.
pub fn step(&mut self) -> Result<bool> {
tracing::trace!("step {}", self.steps);
tracing::debug!("step {}", self.steps.load(Relaxed));

let tick = self.config.tick;
let mut is_finished = true;
Expand Down Expand Up @@ -386,12 +410,12 @@ impl<'a> Sim<'a> {
}

self.elapsed += tick;
self.steps += 1;
let steps = self.steps.fetch_add(1, Relaxed) + 1;

if self.elapsed > self.config.duration && !is_finished {
return Err(format!(
"Ran for duration: {:?} steps: {} without completing",
self.config.duration, self.steps,
self.config.duration, steps,
))?;
}

Expand Down