Skip to content

Instantly share code, notes, and snippets.

@Ryan1729
Last active April 29, 2020 16:38
Show Gist options
  • Save Ryan1729/72becbd5328629c06575f2f98632deea to your computer and use it in GitHub Desktop.
Save Ryan1729/72becbd5328629c06575f2f98632deea to your computer and use it in GitHub Desktop.
A toy program that uses two threads to test multi-threaded debugging
use std::thread;
use std::time::{Duration, Instant};
use std::sync::mpsc::channel;
fn main() {
let (in1, out1) = channel();
let (in2, out2) = channel();
thread::Builder::new()
.name("1st".into())
.spawn(move || in1.send(count_loops()));
thread::Builder::new()
.name("2nd".into())
.spawn(move || in2.send(count_loops()));
println!(
"thread1 looped {} times and thread 2 looped {} times.",
out1.recv().unwrap(),
out2.recv().unwrap(),
);
}
fn count_loops() -> usize {
let current = thread::current();
let name = current.name().unwrap();
let start = Instant::now();
let duration = Duration::from_secs(10);
let mut count = 0;
while Instant::now().duration_since(start) < duration {
// This match lets us add breakpoints that only a single thread will hit.
match name {
"1st" => {
count += 1;
}
"2nd" => {
count += 1;
}
_ => {}
}
}
count
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment