rqbit/crates/librqbit/src/spawn_utils.rs

42 lines
1.2 KiB
Rust
Raw Normal View History

2023-12-03 12:14:50 +00:00
/// Spawn a future inside a tracing span, while logging it's start,
/// finish and periodically logging if it's still alive.
#[track_caller]
2023-11-19 12:50:11 +00:00
pub fn spawn(
2023-11-25 02:36:19 +00:00
_name: &str,
2023-11-19 12:50:11 +00:00
span: tracing::Span,
fut: impl std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
2023-11-24 18:28:46 +00:00
) -> tokio::task::JoinHandle<()> {
2023-11-25 15:15:16 +00:00
librqbit_core::spawn_utils::spawn(span, fut)
}
2021-07-01 19:17:44 +01:00
#[derive(Clone, Copy, Debug)]
2023-12-03 12:14:50 +00:00
pub(crate) struct BlockingSpawner {
2021-07-01 19:17:44 +01:00
allow_tokio_block_in_place: bool,
}
impl BlockingSpawner {
pub fn new(allow_tokio_block_in_place: bool) -> Self {
Self {
allow_tokio_block_in_place,
}
}
pub fn spawn_block_in_place<F: FnOnce() -> R, R>(&self, f: F) -> R {
if self.allow_tokio_block_in_place {
return tokio::task::block_in_place(f);
}
2021-07-02 10:21:19 +01:00
f()
2021-07-01 19:17:44 +01:00
}
}
2023-11-19 22:48:19 +00:00
impl Default for BlockingSpawner {
fn default() -> Self {
let allow_block_in_place = match tokio::runtime::Handle::current().runtime_flavor() {
tokio::runtime::RuntimeFlavor::CurrentThread => false,
tokio::runtime::RuntimeFlavor::MultiThread => true,
_ => true,
};
Self::new(allow_block_in_place)
}
}