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

threadpool: add panic_handler #1052

Merged
merged 6 commits into from
Apr 21, 2019
Merged
Show file tree
Hide file tree
Changes from 5 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
30 changes: 30 additions & 0 deletions tokio-threadpool/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use shutdown::ShutdownTrigger;
use thread_pool::ThreadPool;
use worker::{self, Worker, WorkerId};

use std::any::Any;
use std::cmp::max;
use std::error::Error;
use std::fmt;
Expand Down Expand Up @@ -106,6 +107,7 @@ impl Builder {
around_worker: None,
after_start: None,
before_stop: None,
catch_panics: None,
},
new_park,
}
Expand Down Expand Up @@ -199,6 +201,34 @@ impl Builder {
self
}

/// Sets a callback to be triggered when a panic during a future bubbles up
/// to Tokio. By default Tokio catches these panics, and they will be
/// ignored. The parameter passed to this callback is the same error value
/// returned from std::panic::catch_unwind(). To abort the process on
/// panics, use std::panic::resume_unwind() in this callback as shown
/// below.
///
/// # Examples
///
/// ```
/// # extern crate tokio_threadpool;
/// # extern crate futures;
/// # use tokio_threadpool::Builder;
///
/// # pub fn main() {
/// let thread_pool = Builder::new()
/// .catch_panics(|err| std::panic::resume_unwind(err))
/// .build();
/// # }
/// ```
pub fn catch_panics<F>(&mut self, f: F) -> &mut Self
where
F: Fn(Box<Any + Send>) + Send + Sync + 'static,
{
self.config.catch_panics = Some(Arc::new(f));
self
}

/// Set name prefix of threads spawned by the scheduler
///
/// Thread name prefix is used for generating thread names. For example, if
Expand Down
2 changes: 2 additions & 0 deletions tokio-threadpool/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use callback::Callback;

use std::any::Any;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
Expand All @@ -14,6 +15,7 @@ pub(crate) struct Config {
pub around_worker: Option<Callback>,
pub after_start: Option<Arc<Fn() + Send + Sync>>,
pub before_stop: Option<Arc<Fn() + Send + Sync>>,
pub catch_panics: Option<Arc<Fn(Box<Any + Send>) + Send + Sync>>,
}

/// Max number of workers that can be part of a pool. This is the most that can
Expand Down
6 changes: 6 additions & 0 deletions tokio-threadpool/src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,12 @@ impl Task {
// Transition to the completed state
self.state.store(State::Complete.into(), Release);

if let Err(panic_err) = res {
if let Some(ref f) = unpark.pool.config.catch_panics {
f(panic_err);
}
}

Run::Complete
}
Ok(Ok(Async::NotReady)) => {
Expand Down
17 changes: 17 additions & 0 deletions tokio-threadpool/tests/threadpool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,23 @@ fn panic_in_task() {
pool.shutdown_on_idle().wait().unwrap();
}

#[test]
fn count_catch_panics() {
let counter = Arc::new(AtomicUsize::new(0));
let counter_ = counter.clone();
let pool = tokio_threadpool::Builder::new()
.catch_panics(move |_err| {
// We caught a panic.
counter_.fetch_add(1, Relaxed);
})
.build();
// Spawn a future that will panic.
pool.spawn(lazy(|| -> Result<(), ()> { panic!() }));
pool.shutdown_on_idle().wait().unwrap();
let counter = counter.load(Relaxed);
assert_eq!(counter, 1);
}

#[test]
fn multi_threadpool() {
use futures::sync::oneshot;
Expand Down