1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
// SPDX-License-Identifier: MIT OR Apache-2.0
/*!
# some_executor

Rust made the terrible mistake of not having an async executor in std. Worse, there is no
trait for executors to implement, and no API for async code to expect. So everyone writes
their code against one specific executor, and it's always tokio. But tokio has too many
drawbacks to be the universal choice, and the other executors are too cumbersome to be
practical. Async rust is stuck in limbo.
There are many proposals to fix this. This one's mine.
`some_executor` is a small crate that sits between the code that *has* futures and the code
that *runs* them:
* **If you spawn futures**, you get one obvious `spawn` that works on "some" executor: a
generic argument, a stored trait object, the executor your caller is already running on,
or a program-wide global. Whichever you pick, you get back an observer you can await,
poll, detach, or drop to cancel.
* **If you write an executor**, you implement one trait, and cancellation, task-locals,
observers, priorities and hints are done for you. You get to focus on scheduling.
* **If you write async code**, you get the featureset that (in my opinion) is table stakes for
async rust: cancellation, task-locals, priorities, execution hints, task IDs and labels.
They work the same on every executor, because the executor doesn't implement them; this
crate does.
There is also a built-in fallback executor, so all of this works out of the box. It is not
good, but it is always there; when you want a real one, see the reference executors below.
# Quick start
```
use some_executor::SomeExecutor;
use some_executor::current_executor::current_executor;
use some_executor::observer::FinishedObservation;
use some_executor::task::{Configuration, Task};
# // Runs on the event loop on wasm32 and blocks natively. It cannot be a plain
# // block_on: on the browser main thread that would starve the event loop the
# // fallback executor needs to start its worker. See "Crossing from sync into async".
# wasm_lite_std::async_doctest!(async {
// A Task is a future plus a label and some scheduling metadata.
let task = Task::without_notifications(
"add".to_string(),
Configuration::default(),
async { 2 + 2 },
);
// Spawn it on whatever executor is current: the one this task is running on,
// else the thread's, else the global one, else the built-in fallback.
let mut executor = current_executor();
let observer = executor.spawn(task);
// The observer is a Future. Dropping it instead would cancel the task.
match observer.await {
FinishedObservation::Ready(value) => assert_eq!(value, 4),
FinishedObservation::Cancelled => unreachable!(),
}
# });
```
The rest of this page is organized by what you are trying to do.
# Spawning tasks
Every path to spawning starts with a [`Task`]: your future, a `String` label, and a
[`Configuration`]. Then pick how you want to get hold of an executor.
| You want to... | Use |
|-----------------------------------------------------------|----------------------------------------------------------------------------|
| Take an executor as a generic argument and monomorphize | [`SomeExecutorExt`] (or [`StaticExecutorExt`], [`LocalExecutorExt`]) |
| Store an executor in a struct, erasing its type | [`DynExecutor`], [`DynStaticExecutor`], [`SomeLocalExecutor`] |
| Borrow the executor your caller is already running on | [`current_executor`], or [`Task::spawn_current`] for fire-and-forget |
| Use the executor pinned to this thread | [`thread_executor`], [`thread_static_executor`], [`thread_local_executor`] |
| Spawn from nowhere in particular (a signal handler, say) | [`global_executor`] |
Whichever you use, `spawn` returns an [`Observer`] (usually a [`TypedObserver`]):
* `.await` it to get a [`FinishedObservation`]: the task's output, or `Cancelled`.
* Call [`observe`](Observer::observe) to peek without waiting.
* Call [`detach`](Observer::detach) to let the task run to completion unobserved.
* Drop it to request cancellation. Cancellation is cooperative: the task sees it through
[`IS_CANCELLED`], and executors may stop polling.
## Which executor is "current"?
[`current_executor`] walks a fixed hierarchy and always returns something:
1. The executor the current task was spawned on ([`TASK_EXECUTOR`]).
2. The executor set for this thread with [`set_thread_executor`].
3. The program-wide executor set with [`set_global_executor`].
4. The built-in fallback executor.
The fallback executor exists so that libraries built on this crate work with zero
configuration. It prints a warning when used, because it is not production quality; install
a real one (see [reference executors](#reference-executors)) with [`set_global_executor`] or
[`set_thread_executor`]. Set `SOME_EXECUTOR_BUILTIN_SHOULD_PANIC=1` to make the fallback
panic instead, which is a good way to find places you forgot to do that.
## Three flavors of executor
Executors differ in what futures they can accept. This crate models the three cases that
come up in practice, each with a generic (`*Ext`) trait for static dispatch and an object-safe
base trait for dynamic dispatch:
| Futures are... | Object-safe trait | Generic trait | Typical executor |
|-----------------------------|-----------------------------------------|------------------------|-----------------------------------------------|
| `Send + 'static` | [`SomeExecutor`] (see [`DynExecutor`]) | [`SomeExecutorExt`] | Thread pools; anything that moves work |
| `'static`, not `Send` | [`SomeStaticExecutor`] (see [`DynStaticExecutor`]) | [`StaticExecutorExt`] | Main-thread and single-threaded executors; wasm |
| Neither (`'a` and `!Send`) | [`SomeLocalExecutor`] | [`LocalExecutorExt`] | Executors scoped to a stack frame |
The `Send` and static flavors are cloneable, like a channel sender, and can be discovered
through [`current_executor`] and friends. Local executors are borrowed and cannot be
cloned; the [`SomeLocalExecutor`] docs explain the lifetime parameter and why. If you
don't know which you need, start with [`SomeExecutor`].
## Configuring a task
[`Configuration`] (build one with [`ConfigurationBuilder`]) carries three things an
executor may use, and none of them changes what your future does:
* A [`Hint`]: is this task expected to be I/O-bound, CPU-bound, or unknown?
* A [`Priority`], for executors that schedule by priority.
* A `poll_after` [`Instant`], before which the executor must not poll the task.
Every task also has a label and a [`TaskID`], both visible from inside the task and from its
observer, which makes tracing and logging across executors practical.
## Reference executors
These crates implement the traits above and are the ones I actually use:
* [some_global_executor](https://sealedabstract.com/code/some_global_executor) is a
thread-pool executor for `Send` tasks. It runs on OS threads natively and on web workers
on wasm32, and can install itself as the thread or global executor. If you want one
executor to replace the built-in fallback, this is it.
* [some_local_executor](https://sealedabstract.com/code/some_local_executor) is a local
executor that runs its tasks on the current thread and can also receive tasks from other
threads.
* [test_executors](https://sealedabstract.com/code/test_executors) provides toy executors good
enough for unit tests.
# Crossing from sync into async
Every program crosses from sync into async exactly once: in `fn main`, in a test, in a CLI
tool, at an FFI callback. Which API you want depends on whether you are *choosing* an
executor or *using* one.
Choosing is [`ExecutorMain`]. It is the trait spelling of "construct the chosen backend,
install it, run this future", so that an `#[some_executor::main(SomeBackend)]` attribute can
expand to something that compiles against a backend the macro has never heard of. It returns
`()` rather than the future's output, which is what makes it implementable on the wasm32 main
thread as well as natively.
Using is [`SomeExecutor::block_on`]. Given an executor -- including the one
[`current_executor`] hands you -- it drives a future to completion and returns its output,
blocking the calling thread:
```
use some_executor::SomeExecutor;
use some_executor::current_executor::current_executor;
# // A doctest runs on the browser main thread, which cannot block; on wasm32 this
# // runs the body on a worker, where it can. Natively it just calls the closure.
# wasm_lite_std::worker_doctest!(|| {
let mut executor = current_executor();
assert_eq!(executor.block_on(async { 2 + 2 }), 4);
# });
```
Underneath both is the free [`block_on`](fn@block_on) function, which polls a future in place
on the calling thread with no executor involved. Because the future never leaves the thread,
it needs neither `Send` nor `'static` and may borrow from the stack -- unlike spawning:
```
# wasm_lite_std::worker_doctest!(|| {
let name = String::from("world");
let greeting = some_executor::block_on(async { format!("hello {}", name.as_str()) });
assert_eq!(greeting, "hello world");
# });
```
Blocking is not universally available, which is why the entry point and the primitive are
separate. It works whenever the blocking thread can keep driving every scheduler the future
depends on: another thread is doing the work, or the executor owns its own loop and runs it
here. It cannot work when the wakeups come from a scheduler this thread can only run by
unwinding -- the browser main thread, where the JavaScript event loop delivers every timer,
promise and worker message. [`block_on`](fn@block_on) panics there with an explanation
rather than hanging the tab; a wasm32 worker has no such problem, and [`ExecutorMain`] is the
portable choice for an entry point.
# Writing async code
Mostly, write the code you want to write. Nothing here requires you to know which executor
you are running on. What you get on top:
* [`task_local!`] declares task-local storage, comparable to `thread_local!` or tokio's
`task_local!`, with `scope`, `get`, `set` and immutable (`static const`) variants.
* Built-in task-locals describe the current task: [`TASK_ID`], [`TASK_LABEL`],
[`TASK_PRIORITY`], and [`IS_CANCELLED`].
* [`IS_CANCELLED`] lets long-running work notice a cancellation request and return early.
* [`TASK_EXECUTOR`] and [`TASK_STATIC_EXECUTOR`] hold the executor a task was spawned on, which
is how [`current_executor`] and [`Task::spawn_current`] find it.
```
use some_executor::task_local;
use some_executor::task::{TASK_LABEL, IS_CANCELLED};
task_local! {
static REQUEST_ID: u64;
}
async fn handle() {
let label = TASK_LABEL.with(|l| l.cloned());
let request = REQUEST_ID.get();
// Do a unit of work, then check for cancellation before the next one.
if IS_CANCELLED.with(|c| c.map(|c| c.is_cancelled()).unwrap_or(false)) {
return;
}
let _ = (label, request);
}
```
# Implementing an executor
An executor is anything that accepts a [`Task`] and polls it. In outline:
1. Implement [`SomeExecutor`] (for `Send` futures), [`SomeStaticExecutor`] (for `'static`,
`!Send` futures) and/or [`SomeLocalExecutor`] (for borrowed futures). Add the matching
`*Ext` marker trait if your executor is `Clone`.
2. In your `spawn`, call [`Task::spawn`] (or `spawn_static` / `spawn_local`) with `&mut self`.
You get back a [`SpawnedTask`] to schedule and an observer to hand to the caller.
3. Poll the spawned task. Its `poll` takes an executor context so that
[`current_executor`] works inside the task; the spawned task itself installs task-locals,
reports completion to the observer, and stops early on cancellation.
4. Respect [`poll_after`]: do not poll before that instant. Sleep, defer, re-queue,
whatever fits your design. This is the main gotcha.
5. Optionally implement [`ExecutorNotified`] to be told when a task's observer requests
cancellation, so you can drop it early instead of discovering that on the next poll.
6. Optionally register yourself with [`set_thread_executor`] / [`set_global_executor`] (or the
static and local equivalents) so that [`current_executor`] finds you.
7. If your executor runs tasks on the calling thread, override
[`SomeExecutor::block_on_objsafe`]. The default parks the caller, which is correct for a
thread pool and a deadlock for a current-thread executor; run your own polling loop until
the future resolves instead. Implement [`ExecutorMain`] too, so `#[some_executor::main]`
can name you.
For static executors, [`static_support`] provides [`OwnedSomeStaticExecutorErasingNotifier`]
to erase your notifier type into the common [`DynStaticExecutor`] shape. For the object-safe
methods (`spawn_objsafe` and friends), the `ObjSafe*` and `Boxed*` type aliases at the crate
root spell out the erased types so you don't have to.
# Compared with `executor-trait`
One way to understand this crate is as an alternative to
[executor-trait](https://crates.io/crates/executor-trait/). I like it a lot; here is why I
made this instead:
1. To support futures whose output isn't `()`.
2. To avoid boxing futures where it isn't necessary.
3. To carry hints and priorities to the executor.
4. To provide task-locals and the other features async code actually needs.
5. To support cancellation much more robustly.
Philosophically, `executor-trait` ships the lowest common denominator that every executor can
support. This crate ships the **highest common denominator that all async code can use**,
together with **polyfills and fallbacks so every executor can offer it**, even ones that don't
support a feature natively. It is straightforward to implement either crate's API in terms
of the other, so the two can be used together.
# wasm32
`wasm32-unknown-unknown` is a first-class target, with and without atomics. Timing uses
[`Instant`], which is `std::time::Instant` natively and a web-clock on wasm, and the fallback
executor schedules through the browser event loop.
# Status
This interface is unstable and may change.
[`Task`]: task::Task
[`Task::spawn`]: task::Task::spawn
[`Task::spawn_current`]: task::Task::spawn_current
[`TaskID`]: task::TaskID
[`SpawnedTask`]: task::SpawnedTask
[`Configuration`]: task::Configuration
[`ConfigurationBuilder`]: task::ConfigurationBuilder
[`Observer`]: observer::Observer
[`TypedObserver`]: observer::TypedObserver
[`FinishedObservation`]: observer::FinishedObservation
[`ExecutorNotified`]: observer::ExecutorNotified
[`current_executor`]: current_executor::current_executor
[`thread_executor`]: thread_executor::thread_executor
[`thread_static_executor`]: thread_executor::thread_static_executor
[`thread_local_executor`]: thread_executor::thread_local_executor
[`set_thread_executor`]: thread_executor::set_thread_executor
[`global_executor`]: global_executor::global_executor
[`set_global_executor`]: global_executor::set_global_executor
[`OwnedSomeStaticExecutorErasingNotifier`]: static_support::OwnedSomeStaticExecutorErasingNotifier
[`poll_after`]: task::Task::poll_after
[`TASK_ID`]: task::TASK_ID
[`TASK_LABEL`]: task::TASK_LABEL
[`TASK_PRIORITY`]: task::TASK_PRIORITY
[`TASK_EXECUTOR`]: task::TASK_EXECUTOR
[`TASK_STATIC_EXECUTOR`]: task::TASK_STATIC_EXECUTOR
[`IS_CANCELLED`]: task::IS_CANCELLED
[`Hint`]: hint::Hint
[`current_executor`]: current_executor::current_executor
[`global_executor`]: global_executor::global_executor
*/
/// Turns an `async fn main` into a `fn main` that installs an executor and runs
/// it. See [`entry_point`] for the trait it expands to a call on.
///
/// ```no_run
/// # // no_run because: the attribute generates this doctest's own `fn main`, so
/// # // running it would install a process-wide executor inside the test harness.
/// #[some_executor::main]
/// async fn main() {
/// println!("hello");
/// }
/// ```
pub use main;
/// Platform-appropriate instant type for time measurements.
///
/// This is a re-export of either `std::time::Instant` (on native platforms) or
/// `web_time::Instant` (on wasm32), providing a unified interface for time-related
/// operations across all supported platforms.
///
/// Use this type for task scheduling and timing operations within the executor framework.
pub use Instant;
/// Re-exported so `some_executor::block_on(..)` works without importing the module.
pub use block_on;
/// Re-exported so backends can `impl some_executor::ExecutorMain for ..`.
pub use ExecutorMain;
/// Reports a misuse the crate can detect but not prevent.
///
/// Prints `message` to stderr (or the browser console), or panics with it if
/// `SOME_EXECUTOR_BUILTIN_SHOULD_PANIC` is set to `1`, `true`, or `yes`. The escalation
/// switch exists because these conditions are usually configuration mistakes, and a
/// panic in development is easier to act on than a line of output in a busy log.
pub
/// Task priority for scheduling hints.
///
/// This is a re-export of the priority crate's Priority type,
/// allowing executors to make scheduling decisions based on task priority.
pub type Priority = Priority;
use crate;
use crateTask;
use Any;
use Infallible;
use Debug;
use Future;
use Pin;
// Type aliases for complex types to satisfy clippy::type_complexity warnings
/// Type alias for a boxed future that outputs boxed Any and is Send + 'static.
///
/// This type is used for type-erased futures that can be sent between threads.
/// It's primarily used internally for object-safe trait implementations.
pub type BoxedSendFuture =
;
/// Type alias for a boxed observer notifier that handles Send Any values.
///
/// This type provides notifications when a type-erased Send task completes.
pub type BoxedSendObserverNotifier = ;
/// Type alias for a Task that can be used with object-safe spawning.
///
/// This allows spawning type-erased tasks through trait objects,
/// enabling dynamic dispatch when concrete types aren't known at compile time.
pub type ObjSafeTask = ;
/// Type alias for a boxed observer that handles Send Any values.
///
/// This observer can be used to track the status and result of type-erased Send tasks.
pub type BoxedSendObserver = ;
/// Type alias for a future that returns a boxed observer for Send Any values.
///
/// Used for async spawning methods that return observers asynchronously.
pub type BoxedSendObserverFuture<'s> = ;
/// Type alias for the type-erased future accepted by [`SomeExecutor::block_on_objsafe`].
///
/// Unlike [`BoxedSendFuture`] this is neither `Send` nor `'static`: `block_on` polls the
/// future in place on the calling thread, so it never has to move anywhere and may
/// borrow from the caller's stack. Only the *output* is erased to `Box<dyn Any + Send>`,
/// which is what costs `F::Output: Send + 'static`.
pub type BoxedBlockOnFuture<'f> = ;
/// Type alias for a boxed future that outputs boxed Any (non-Send).
///
/// This type is used for type-erased futures that are local to a thread.
pub type BoxedLocalFuture = ;
/// Type alias for a boxed observer notifier that handles Any values (non-Send).
///
/// This type provides notifications when a type-erased local task completes.
pub type BoxedLocalObserverNotifier = ;
/// Type alias for a Task that can be used with local object-safe spawning.
///
/// This allows spawning type-erased !Send tasks through trait objects.
pub type ObjSafeLocalTask = ;
/// Type alias for a boxed observer that handles Any values (non-Send).
///
/// This observer can be used to track the status and result of type-erased local tasks.
pub type BoxedLocalObserver =
;
/// Type alias for a future that returns a boxed observer for local Any values.
///
/// Used for async spawning methods that return local observers asynchronously.
pub type BoxedLocalObserverFuture<'s> = ;
/// Type alias for a boxed future that outputs boxed Any and is 'static but not Send.
///
/// This type is used for type-erased futures with static lifetime but no Send requirement.
pub type BoxedStaticFuture = ;
/// Type alias for a boxed observer notifier that handles 'static Any values (non-Send).
///
/// This type provides notifications when a type-erased static task completes.
pub type BoxedStaticObserverNotifier = ;
/// Type alias for a Task that can be used with static object-safe spawning.
///
/// This allows spawning type-erased 'static tasks without Send requirement.
pub type ObjSafeStaticTask = ;
/// Type alias for a boxed observer that handles 'static Any values (non-Send).
///
/// This observer can be used to track the status and result of type-erased static tasks.
pub type BoxedStaticObserver =
;
/// Type alias for a future that returns a boxed observer for static Any values.
///
/// Used for async spawning methods that return static observers asynchronously.
pub type BoxedStaticObserverFuture<'s> = ;
/*
Design notes.
Send is required because we often want to take this trait object and port it to another thread, etc.
Sync is required to have a global executor.
Clone is required so that we can get copies for sending.
PartialEq could be used to compare runtimes, but I can't imagine anyone needs it
PartialOrd, Ord what does it mean?
Hash might make sense if we support eq but again, I can't imagine anyone needs it.
Debug
I think all the rest are nonsense.
*/
/// A trait targeting 'some' executor.
///
/// Code targeting this trait can spawn tasks on an executor without knowing which executor it is.
/// This is the core abstraction that allows writing executor-agnostic async code.
///
/// If possible, use the [`SomeExecutorExt`] trait instead for a more ergonomic API.
/// This trait is primarily useful when you need an object-safe trait for dynamic dispatch.
///
/// # Example
///
/// ```
/// # use some_executor::{SomeExecutor, task::Task};
/// # use std::any::Any;
/// # use std::pin::Pin;
/// # use std::future::Future;
/// # use std::convert::Infallible;
/// # fn example(exec: &mut dyn SomeExecutor<ExecutorNotifier = Infallible>) {
/// let future = Box::new(async { Box::new(42) as Box<dyn Any + Send> });
/// let task = Task::new_objsafe(
/// "example".to_string(),
/// future,
/// Default::default(),
/// None
/// );
/// let observer = exec.spawn_objsafe(task);
/// // Can track task completion via observer
/// # }
/// ```
/// A non-objsafe descendant of [SomeExecutor].
///
/// This trait provides a more ergonomic interface for executors, but is not object-safe
/// due to the Clone requirement. This is the preferred trait for most use cases where
/// you know the executor type at compile time.
///
/// # Example
///
/// ```
/// # use some_executor::{SomeExecutorExt, task::Task};
/// # use std::future::Future;
/// # use std::convert::Infallible;
/// # fn example<E: SomeExecutorExt>(mut exec: E) {
/// let task = Task::<_, Infallible>::without_notifications(
/// "example".to_string(),
/// Default::default(),
/// async { 42 }
/// );
/// let observer = exec.spawn(task);
/// // Type-safe observer for the return value
/// # }
/// ```
/**
A trait for executors that can spawn tasks onto the local thread.
This type can spawn futures that are `!Send`.
# About the lifetime parameter
The lifetime parameter defines the lifetime of the executor itself, which is really the longest lifetime of any future it may be executing.
To understand this, it is helpful to consider 3 cases.
## Multithreaded executors
Multithreaded executors along the lines of [SomeExecutor] generally require their futures to be `'static`.
This is vaguely intuitive in the "it is nice to be able to move the future to another thread" sense,
but in full detail it is less intuitive than it seems.
If a future refers to data on the local stack frame, then the future may dangle if:
1. The user returns upstack before the future completes, this could maybe be resolved with clever lifetimes?
2. The thread panics before the future completes, this is a hard problem.
3. The "thread" is really an async context, which is cancelled before the future completes, this is a hard problem.
4. The thread is terminated by the OS for some reason, this is a hard problem.
For at least reasons 2-4, [SomeExecutor] implicitly requires `'static` futures.
## Local executors, globally-scoped
Now let us consider a local executor with global scope (such as a main thread executor). These executors
disptach onto the local thread but exist for a long time, such as the lifetime of the program. These
types of executors have requirements not so dissimilar from multithreaded executors:
1. The user returns upstack before the future completes. This is probably fine, if we poison the
executor in some way (includingstatically), although care must be taken to ensure that the future's memory does not escape.
For example, in a DMA-type operation where the OS is writing to a buffer independently,
that buffer must not be located on the stack.
2. If the thread panics before the future completes, that's probably fine as well since the executor
is inherently poisoned by the panic. See the DMA-style caveat above.
3. If the async context is cancelled before the future completes, that's a big problem. It is a hard one
to solve because it's not obvious how to poison the executor deterministically.
4. If the thread is terminated by the OS, the executor is poisoned so that's ok.
Due to reason 3, local executors with global scope generally require `'static` futures.
## Local executors, locally scoped
Alternatively we may spin up an executor e.g. on a stack frame, for a specific task. In that case:
1. Returning upstack inherently poisons the executor, with sensible lifetime design/analysis.
2. Panicking poisons the executor.
3. Cancellation posions the executor since the executor is on the same stackframe
4. The thread is terminated by the OS, the executor is poisoned.
In this case, the executor can support non-`'static` futures.
## Overall
In summary, for executors with global scope, `'static' should be chosen as the lifetime parameter.
For executors with local scope, this trait can be implemented for any lifetime.
When in doubt, the `'static` lifetime can be chosen and upgraded later.
*/