From 3bc0c85f3b4cc3eb6de1d23bc3562041b7bf45f9 Mon Sep 17 00:00:00 2001 From: Julian Hofer Date: Mon, 9 Oct 2023 15:35:33 +0200 Subject: [PATCH] Add `spawn_future` and `spawn_future_local` convenience functions A couple of gtk-rs apps currently use utility functions to make spawning futures less verbose. See: - https://docs.rs/gtk-macros/0.3.0/gtk_macros/macro.spawn.html - https://gitlab.gnome.org/GNOME/loupe/-/blob/main/src/util/mod.rs#L251 Exposing these functions via glib should fulfill that need. --- glib/src/functions.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/glib/src/functions.rs b/glib/src/functions.rs index 5b3d65ad3fc1..357a0b73c111 100644 --- a/glib/src/functions.rs +++ b/glib/src/functions.rs @@ -260,3 +260,30 @@ pub fn file_open_tmp( } } } + +// rustdoc-stripper-ignore-next +/// Spawn a new infallible `Future` on the thread-default main context. +/// +/// This can be called from any thread and will execute the future from the thread +/// where main context is running, e.g. via a `MainLoop`. +pub fn spawn_future + Send + 'static>( + f: F, +) -> crate::JoinHandle { + let ctx = crate::MainContext::ref_thread_default(); + ctx.spawn(f) +} + +// rustdoc-stripper-ignore-next +/// Spawn a new infallible `Future` on the thread-default main context. +/// +/// The given `Future` does not have to be `Send`. +/// +/// This can be called only from the thread where the main context is running, e.g. +/// from any other `Future` that is executed on this main context, or after calling +/// `with_thread_default` or `acquire` on the main context. +pub fn spawn_future_local + 'static>( + f: F, +) -> crate::JoinHandle { + let ctx = crate::MainContext::ref_thread_default(); + ctx.spawn_local(f) +}