Skip to content

Commit b2e3470

Browse files
YaZasnyalArtem Vasiliev
and
Artem Vasiliev
authored
FIX: Thread leak in pool (#9)
Co-authored-by: Artem Vasiliev <[email protected]>
1 parent 912c4bc commit b2e3470

File tree

2 files changed

+18
-12
lines changed

2 files changed

+18
-12
lines changed

src/lib.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -160,16 +160,18 @@ impl Threadpool {
160160
if let Some(stack_size) = data.stack_size {
161161
builder = builder.stack_size(stack_size);
162162
}
163+
// Increase the thread count counter
164+
data.thread_count.fetch_add(1, Ordering::SeqCst);
165+
// Create a new sentry watcher
166+
let sentry = Sentry::new(coreid, Arc::downgrade(&data));
167+
// Clone receiver
168+
let receiver = data.receiver.clone();
163169
// Spawn a new worker thread
164170
let _ = builder.spawn(move || {
165-
// Create a new sentry watcher
166-
let sentry = Sentry::new(coreid, &data);
167-
// Increase the thread count counter
168-
data.thread_count.fetch_add(1, Ordering::SeqCst);
169171
// Loop continuously, processing any jobs
170172
loop {
171173
// Pull a message from the job channel
172-
let job = match data.receiver.recv_blocking() {
174+
let job = match receiver.recv_blocking() {
173175
// We received a job to process
174176
Ok(job) => job,
175177
// This threadpool was dropped

src/sentry.rs

+11-7
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
use crate::Data;
22
use crate::Threadpool;
3-
use std::sync::Arc;
3+
use std::sync::Weak;
44

5-
pub(crate) struct Sentry<'a> {
5+
pub(crate) struct Sentry {
66
active: bool,
77
coreid: Option<usize>,
8-
data: &'a Arc<Data>,
8+
data: Weak<Data>,
99
}
1010

11-
impl<'a> Sentry<'a> {
11+
impl Sentry {
1212
/// Create a new sentry tracker
13-
pub fn new(coreid: Option<usize>, data: &'a Arc<Data>) -> Sentry<'a> {
13+
pub fn new(coreid: Option<usize>, data: Weak<Data>) -> Sentry {
1414
Sentry {
1515
data,
1616
coreid,
@@ -23,15 +23,19 @@ impl<'a> Sentry<'a> {
2323
}
2424
}
2525

26-
impl Drop for Sentry<'_> {
26+
impl Drop for Sentry {
2727
fn drop(&mut self) {
28+
let Some(data) = self.data.upgrade() else {
29+
return;
30+
};
31+
2832
// If this sentry was still active,
2933
// then the task panicked without
3034
// properly cancelling the sentry,
3135
// so we should start a new thread.
3236
if self.active {
3337
// Spawn another new thread
34-
Threadpool::spin_up(self.coreid, self.data.clone());
38+
Threadpool::spin_up(self.coreid, data.clone());
3539
}
3640
}
3741
}

0 commit comments

Comments
 (0)