Skip to content

Commit 4f05db6

Browse files
committed
Stop BackgroundProcessor's thread on drop
Without stopping the thread when BackgroundProcessor is dropped, it will run free. In the context of language bindings, it is difficult to know how long references held by the thread should live. Implement Drop to stop the thread just as is done when explicitly calling stop().
1 parent d9fa8f1 commit 4f05db6

File tree

1 file changed

+18
-4
lines changed
  • lightning-background-processor/src

1 file changed

+18
-4
lines changed

lightning-background-processor/src/lib.rs

+18-4
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub struct BackgroundProcessor {
4343
stop_thread: Arc<AtomicBool>,
4444
/// May be used to retrieve and handle the error if `BackgroundProcessor`'s thread
4545
/// exits due to an error while persisting.
46-
pub thread_handle: JoinHandle<Result<(), std::io::Error>>,
46+
pub thread_handle: Option<JoinHandle<Result<(), std::io::Error>>>,
4747
}
4848

4949
#[cfg(not(test))]
@@ -158,13 +158,27 @@ impl BackgroundProcessor {
158158
}
159159
}
160160
});
161-
Self { stop_thread: stop_thread_clone, thread_handle: handle }
161+
Self { stop_thread: stop_thread_clone, thread_handle: Some(handle) }
162162
}
163163

164164
/// Stop `BackgroundProcessor`'s thread.
165-
pub fn stop(self) -> Result<(), std::io::Error> {
165+
pub fn stop(mut self) -> Result<(), std::io::Error> {
166+
assert!(self.thread_handle.is_some());
167+
self.stop_and_join_thread()
168+
}
169+
170+
fn stop_and_join_thread(&mut self) -> Result<(), std::io::Error> {
166171
self.stop_thread.store(true, Ordering::Release);
167-
self.thread_handle.join().unwrap()
172+
match self.thread_handle.take() {
173+
Some(handle) => handle.join().unwrap(),
174+
None => Ok(()),
175+
}
176+
}
177+
}
178+
179+
impl Drop for BackgroundProcessor {
180+
fn drop(&mut self) {
181+
self.stop_and_join_thread().unwrap();
168182
}
169183
}
170184

0 commit comments

Comments
 (0)