From b9a37f5362844bc745a3781161b53ecd58350981 Mon Sep 17 00:00:00 2001 From: 0xd34d10cc <0xd34d10cc@gmail.com> Date: Tue, 21 Dec 2021 17:51:11 +0000 Subject: [PATCH 1/3] Add blocking_recv method to oneshot::Receiver --- tokio/src/sync/oneshot.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index cfc92259d39..40986652a83 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -1014,6 +1014,35 @@ impl Receiver { self.inner = None; result } + + /// Blocking receive to call outside of asynchronous contexts. + /// + /// # Panics + /// + /// This function panics if called within an asynchronous execution + /// context. + /// + /// # Examples + /// + /// ``` + /// use std::thread; + /// use tokio::sync::oneshot; + /// + /// #[tokio::main] + /// async fn main() { + /// let (tx, rx) = oneshot::channel::(); + /// + /// let sync_code = thread::spawn(move || { + /// assert_eq!(Some(10), rx.blocking_recv()); + /// }); + /// + /// let _ = tx.send(10); + /// sync_code.join().unwrap(); + /// } + /// ``` + pub fn blocking_recv(self) -> Option { + crate::future::block_on(self).ok() + } } impl Drop for Receiver { From ded4e129dc189c7b9eb52e4f1d85c994990d2f1b Mon Sep 17 00:00:00 2001 From: 0xd34d10cc <0xd34d10cc@gmail.com> Date: Tue, 21 Dec 2021 19:59:26 +0000 Subject: [PATCH 2/3] Compile oneshot::Receiver::blocking_recv() only when "sync" feature is enabled (future::block_on is exported only if it is enabled, but sync module is compiled in any case for use within tokio) --- tokio/src/sync/oneshot.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index 40986652a83..0c7e00e50b7 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -1040,6 +1040,7 @@ impl Receiver { /// sync_code.join().unwrap(); /// } /// ``` + #[cfg(feature = "sync")] pub fn blocking_recv(self) -> Option { crate::future::block_on(self).ok() } From b1c153f82ce171a153d75bc6eedb81bf940e6a18 Mon Sep 17 00:00:00 2001 From: 0xd34d10cc <0xd34d10cc@gmail.com> Date: Sun, 2 Jan 2022 20:22:31 +0000 Subject: [PATCH 3/3] Return Result instead of Option from oneshot::Receiver::blocking_recv() --- tokio/src/sync/oneshot.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index 0c7e00e50b7..2240074e733 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -1033,7 +1033,7 @@ impl Receiver { /// let (tx, rx) = oneshot::channel::(); /// /// let sync_code = thread::spawn(move || { - /// assert_eq!(Some(10), rx.blocking_recv()); + /// assert_eq!(Ok(10), rx.blocking_recv()); /// }); /// /// let _ = tx.send(10); @@ -1041,8 +1041,8 @@ impl Receiver { /// } /// ``` #[cfg(feature = "sync")] - pub fn blocking_recv(self) -> Option { - crate::future::block_on(self).ok() + pub fn blocking_recv(self) -> Result { + crate::future::block_on(self) } }