Skip to content

Commit 6ff6f85

Browse files
committed
imp(pyspy): use AtomicBool instead of Mutex
1 parent b60b1a6 commit 6ff6f85

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

pyroscope_backends/src/pyspy.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,15 @@ use super::{
44
error::{BackendError, Result},
55
types::{Backend, StackFrame, StackTrace, State},
66
};
7-
use py_spy::{
8-
config::Config,
9-
sampler::{Sample, Sampler},
10-
};
7+
use py_spy::{config::Config, sampler::Sampler};
118
use std::{
12-
collections::HashMap,
139
sync::{
14-
mpsc::{channel, sync_channel, Receiver, Sender, SyncSender},
10+
atomic::{AtomicBool, Ordering},
1511
Arc, Mutex,
1612
},
1713
thread::JoinHandle,
1814
};
1915

20-
// TODO: state for the thread + stop function
21-
// TODO: refactor fold function
22-
2316
/// Pyspy Configuration
2417
#[derive(Debug, Clone)]
2518
pub struct PyspyConfig {
@@ -128,7 +121,8 @@ pub struct Pyspy {
128121
sampler_config: Option<Config>,
129122
/// Sampler thread
130123
sampler_thread: Option<JoinHandle<Result<()>>>,
131-
running: Arc<Mutex<bool>>,
124+
/// Atomic flag to stop the sampler
125+
running: Arc<AtomicBool>,
132126
}
133127

134128
impl std::fmt::Debug for Pyspy {
@@ -146,7 +140,7 @@ impl Pyspy {
146140
config,
147141
sampler_config: None,
148142
sampler_thread: None,
149-
running: Arc::new(Mutex::new(false)),
143+
running: Arc::new(AtomicBool::new(false)),
150144
}
151145
}
152146
}
@@ -202,7 +196,7 @@ impl Backend for Pyspy {
202196

203197
let running = Arc::clone(&self.running);
204198
// set running to true
205-
*running.lock().unwrap() = true;
199+
running.store(true, Ordering::Relaxed);
206200

207201
let buffer = self.buffer.clone();
208202

@@ -211,7 +205,7 @@ impl Backend for Pyspy {
211205
self.sampler_thread = Some(std::thread::spawn(move || {
212206
let sampler = Sampler::new(config.pid.unwrap(), &config)?;
213207

214-
let isampler = sampler.take_while(|x| *running.lock().unwrap());
208+
let isampler = sampler.take_while(|_x| running.load(Ordering::Relaxed));
215209

216210
for sample in isampler {
217211
for trace in sample.traces {
@@ -245,7 +239,7 @@ impl Backend for Pyspy {
245239
}
246240

247241
// set running to false
248-
*self.running.lock().unwrap() = false;
242+
self.running.store(false, Ordering::Relaxed);
249243

250244
// wait for sampler thread to finish
251245
self.sampler_thread.take().unwrap().join().unwrap()?;

0 commit comments

Comments
 (0)