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
//! Structured task ownership.
use std::marker::PhantomData;
use crate::{JoinHandle, Result, Runtime, RuntimeSnapshot};
/// A lexical owner for transferable tasks dispatched to persistent carriers.
pub struct Scope<'runtime> {
runtime: &'runtime Runtime,
id: u64,
_invariant: PhantomData<&'runtime mut &'runtime ()>,
}
impl<'runtime> Scope<'runtime> {
pub(crate) fn new(runtime: &'runtime Runtime, id: u64) -> Self {
Self {
runtime,
id,
_invariant: PhantomData,
}
}
/// Spawns a named virtual thread owned by this scope.
///
/// The closure and result must be `Send + 'static`. Non-Send values may be
/// created inside the task and survive suspension because its stack never migrates.
/// Use local_scope inside a virtual thread for borrowed, non-Send children.
///
/// ```compile_fail
/// let runtime = vthread::Runtime::new().unwrap();
/// let local = std::rc::Rc::new(42);
/// runtime.run_scope(|scope| {
/// scope.spawn("not-transferable", move || *local)?;
/// Ok(())
/// }).unwrap();
/// ```
pub fn spawn<T, F>(&self, name: impl Into<String>, entry: F) -> Result<JoinHandle<T>>
where
F: FnOnce() -> T + Send + 'static,
T: Send + 'static,
{
self.spawner().spawn(name, entry)
}
/// Spawns a child with a deadline bounded by its owner and same-runtime caller.
pub fn spawn_with<T: Send + 'static>(
&self,
options: crate::SpawnOptions,
name: impl Into<String>,
entry: impl FnOnce() -> T + Send + 'static,
) -> Result<JoinHandle<T>> {
self.spawner().spawn_with(options, name, entry)
}
/// Returns a transferable admission capability; it cannot extend this scope's lifetime.
pub fn spawner(&self) -> crate::Spawner {
crate::Spawner::new(&self.runtime.shared, self.id)
}
/// Returns the cooperative cancellation token inherited by this scope's children.
pub fn cancellation_token(&self) -> crate::CancellationToken {
self.runtime
.shared
.scope_options(self.id)
.expect("live scope")
.cancellation
}
/// Requests cooperative cancellation of every child in this scope.
pub fn cancel(&self) {
self.cancellation_token().cancel();
}
/// Returns the inherited monotonic deadline.
pub fn deadline(&self) -> Option<std::time::Instant> {
self.runtime
.shared
.scope_options(self.id)
.expect("live scope")
.deadline
}
/// Returns diagnostics for all tasks currently retained by the runtime.
pub fn runtime_snapshot(&self) -> RuntimeSnapshot {
self.runtime.snapshot()
}
}
#[cfg(test)]
#[path = "scope_test.rs"]
mod scope_test;