Skip to content

Commit 856e890

Browse files
committed
add Task::spawner
Signed-off-by: Marc-Antoine Perennou <Marc-Antoine@Perennou.com>
1 parent 73257d2 commit 856e890

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/lib.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,35 @@ impl<T> Task<T> {
488488
}
489489
}
490490

491+
impl Task<()> {
492+
/// Get a Spawner for the current multi-threaded executor.
493+
///
494+
/// If called from an [`Executor`], get its Spawner.
495+
///
496+
/// Otherwise, this method panics.
497+
///
498+
/// # Examples
499+
///
500+
/// ```
501+
/// use async_executor::{Executor, Task};
502+
///
503+
/// let ex = Executor::new();
504+
///
505+
/// ex.run(async {
506+
/// let spawner = Task::<_>::spawner();
507+
/// let task = spawner.spawn(async { 1 + 2 });
508+
/// assert_eq!(task.await, 3);
509+
/// });
510+
/// ```
511+
pub fn spawner() -> Spawner {
512+
if EX.is_set() {
513+
EX.with(|ex| ex.spawner())
514+
} else {
515+
panic!("`Task::spawner()` must be called from an `Executor`")
516+
}
517+
}
518+
}
519+
491520
impl<T> Future for Task<T> {
492521
type Output = T;
493522

0 commit comments

Comments
 (0)