|
1 | 1 | use std::marker::PhantomData;
|
2 | 2 |
|
| 3 | +use crate::runtime::Callback; |
| 4 | + |
3 | 5 | /// [`LocalRuntime`]-only config options
|
4 | 6 | ///
|
5 |
| -/// Currently, there are no such options, but in the future, things like `!Send + !Sync` hooks may |
6 |
| -/// be added. |
7 |
| -/// |
8 | 7 | /// Use `LocalOptions::default()` to create the default set of options. This type is used with
|
9 | 8 | /// [`Builder::build_local`].
|
10 | 9 | ///
|
| 10 | +/// When using [`Builder::build_local`], this overrides any pre-configured options set on the |
| 11 | +/// [`Builder`]. |
| 12 | +/// |
11 | 13 | /// [`Builder::build_local`]: crate::runtime::Builder::build_local
|
12 | 14 | /// [`LocalRuntime`]: crate::runtime::LocalRuntime
|
13 |
| -#[derive(Default, Debug)] |
| 15 | +/// [`Builder`]: crate::runtime::Builder |
| 16 | +#[derive(Default)] |
14 | 17 | #[non_exhaustive]
|
| 18 | +#[allow(missing_debug_implementations)] |
15 | 19 | pub struct LocalOptions {
|
16 | 20 | /// Marker used to make this !Send and !Sync.
|
17 | 21 | _phantom: PhantomData<*mut u8>,
|
| 22 | + |
| 23 | + /// Callback for a worker parking itself |
| 24 | + pub(crate) before_park: Option<Callback>, |
| 25 | + |
| 26 | + /// Callback for a worker unparking itself |
| 27 | + pub(crate) after_unpark: Option<Callback>, |
| 28 | +} |
| 29 | + |
| 30 | +impl LocalOptions { |
| 31 | + /// Executes function `f` just before a thread is parked (goes idle). |
| 32 | + /// `f` is called within the Tokio context, so functions like [`tokio::spawn`](crate::spawn) |
| 33 | + /// can be called, and may result in this thread being unparked immediately. |
| 34 | + /// |
| 35 | + /// This can be used to start work only when the executor is idle, or for bookkeeping |
| 36 | + /// and monitoring purposes. |
| 37 | + /// |
| 38 | + /// This differs from the `Builder::on_thread_park` method in that it accepts a non Send + Sync |
| 39 | + /// closure. |
| 40 | + /// |
| 41 | + /// Note: There can only be one park callback for a runtime; calling this function |
| 42 | + /// more than once replaces the last callback defined, rather than adding to it. |
| 43 | + /// |
| 44 | + /// # Examples |
| 45 | + /// |
| 46 | + /// ``` |
| 47 | + /// # use tokio::runtime::{Builder, LocalOptions}; |
| 48 | + /// # pub fn main() { |
| 49 | + /// let (tx, rx) = std::sync::mpsc::channel(); |
| 50 | + /// let mut opts = LocalOptions::default(); |
| 51 | + /// opts.on_thread_park(move || match rx.recv() { |
| 52 | + /// Ok(x) => println!("Received from channel: {}", x), |
| 53 | + /// Err(e) => println!("Error receiving from channel: {}", e), |
| 54 | + /// }); |
| 55 | + /// |
| 56 | + /// let runtime = Builder::new_current_thread() |
| 57 | + /// .enable_time() |
| 58 | + /// .build_local(opts) |
| 59 | + /// .unwrap(); |
| 60 | + /// |
| 61 | + /// runtime.block_on(async { |
| 62 | + /// tokio::task::spawn_local(async move { |
| 63 | + /// tx.send(42).unwrap(); |
| 64 | + /// }); |
| 65 | + /// tokio::time::sleep(std::time::Duration::from_millis(1)).await; |
| 66 | + /// }) |
| 67 | + /// } |
| 68 | + /// ``` |
| 69 | + pub fn on_thread_park<F>(&mut self, f: F) -> &mut Self |
| 70 | + where |
| 71 | + F: Fn() + 'static, |
| 72 | + { |
| 73 | + self.before_park = Some(std::sync::Arc::new(to_send_sync(f))); |
| 74 | + self |
| 75 | + } |
| 76 | + |
| 77 | + /// Executes function `f` just after a thread unparks (starts executing tasks). |
| 78 | + /// |
| 79 | + /// This is intended for bookkeeping and monitoring use cases; note that work |
| 80 | + /// in this callback will increase latencies when the application has allowed one or |
| 81 | + /// more runtime threads to go idle. |
| 82 | + /// |
| 83 | + /// This differs from the `Builder::on_thread_unpark` method in that it accepts a non Send + Sync |
| 84 | + /// closure. |
| 85 | + /// |
| 86 | + /// Note: There can only be one unpark callback for a runtime; calling this function |
| 87 | + /// more than once replaces the last callback defined, rather than adding to it. |
| 88 | + /// |
| 89 | + /// # Examples |
| 90 | + /// |
| 91 | + /// ``` |
| 92 | + /// # use tokio::runtime::{Builder, LocalOptions}; |
| 93 | + /// # pub fn main() { |
| 94 | + /// let (tx, rx) = std::sync::mpsc::channel(); |
| 95 | + /// let mut opts = LocalOptions::default(); |
| 96 | + /// opts.on_thread_unpark(move || match rx.recv() { |
| 97 | + /// Ok(x) => println!("Received from channel: {}", x), |
| 98 | + /// Err(e) => println!("Error receiving from channel: {}", e), |
| 99 | + /// }); |
| 100 | + /// |
| 101 | + /// let runtime = Builder::new_current_thread() |
| 102 | + /// .enable_time() |
| 103 | + /// .build_local(opts) |
| 104 | + /// .unwrap(); |
| 105 | + /// |
| 106 | + /// runtime.block_on(async { |
| 107 | + /// tokio::task::spawn_local(async move { |
| 108 | + /// tx.send(42).unwrap(); |
| 109 | + /// }); |
| 110 | + /// tokio::time::sleep(std::time::Duration::from_millis(1)).await; |
| 111 | + /// }) |
| 112 | + /// } |
| 113 | + /// ``` |
| 114 | + pub fn on_thread_unpark<F>(&mut self, f: F) -> &mut Self |
| 115 | + where |
| 116 | + F: Fn() + 'static, |
| 117 | + { |
| 118 | + self.after_unpark = Some(std::sync::Arc::new(to_send_sync(f))); |
| 119 | + self |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +// A wrapper type to allow non-Send + Sync closures to be used in a Send + Sync context. |
| 124 | +// This is specifically used for executing callbacks when using a `LocalRuntime`. |
| 125 | +struct UnsafeSendSync<T>(T); |
| 126 | + |
| 127 | +// SAFETY: This type is only used in a context where it is guaranteed that the closure will not be |
| 128 | +// sent across threads. |
| 129 | +unsafe impl<T> Send for UnsafeSendSync<T> {} |
| 130 | +unsafe impl<T> Sync for UnsafeSendSync<T> {} |
| 131 | + |
| 132 | +impl<T: Fn()> UnsafeSendSync<T> { |
| 133 | + fn call(&self) { |
| 134 | + (self.0)() |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +fn to_send_sync<F>(f: F) -> impl Fn() + Send + Sync |
| 139 | +where |
| 140 | + F: Fn(), |
| 141 | +{ |
| 142 | + let f = UnsafeSendSync(f); |
| 143 | + move || f.call() |
18 | 144 | }
|
0 commit comments