Coverage Report

Created: 2026-01-10 06:41

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tokio-1.49.0/src/runtime/park.rs
Line
Count
Source
1
#![cfg_attr(not(feature = "full"), allow(dead_code))]
2
3
use crate::loom::sync::atomic::AtomicUsize;
4
use crate::loom::sync::{Arc, Condvar, Mutex};
5
6
use std::sync::atomic::Ordering::SeqCst;
7
use std::time::Duration;
8
9
#[derive(Debug)]
10
pub(crate) struct ParkThread {
11
    inner: Arc<Inner>,
12
}
13
14
/// Unblocks a thread that was blocked by `ParkThread`.
15
#[derive(Clone, Debug)]
16
pub(crate) struct UnparkThread {
17
    inner: Arc<Inner>,
18
}
19
20
#[derive(Debug)]
21
struct Inner {
22
    state: AtomicUsize,
23
    mutex: Mutex<()>,
24
    condvar: Condvar,
25
}
26
27
const EMPTY: usize = 0;
28
const PARKED: usize = 1;
29
const NOTIFIED: usize = 2;
30
31
tokio_thread_local! {
32
    static CURRENT_PARKER: ParkThread = ParkThread::new();
33
}
34
35
// Bit of a hack, but it is only for loom
36
#[cfg(loom)]
37
tokio_thread_local! {
38
    pub(crate) static CURRENT_THREAD_PARK_COUNT: AtomicUsize = AtomicUsize::new(0);
39
}
40
41
// ==== impl ParkThread ====
42
43
impl ParkThread {
44
2
    pub(crate) fn new() -> Self {
45
2
        Self {
46
2
            inner: Arc::new(Inner {
47
2
                state: AtomicUsize::new(EMPTY),
48
2
                mutex: Mutex::new(()),
49
2
                condvar: Condvar::new(),
50
2
            }),
51
2
        }
52
2
    }
53
54
35.1k
    pub(crate) fn unpark(&self) -> UnparkThread {
55
35.1k
        let inner = self.inner.clone();
56
35.1k
        UnparkThread { inner }
57
35.1k
    }
58
59
0
    pub(crate) fn park(&mut self) {
60
        #[cfg(loom)]
61
        CURRENT_THREAD_PARK_COUNT.with(|count| count.fetch_add(1, SeqCst));
62
0
        self.inner.park();
63
0
    }
64
65
0
    pub(crate) fn park_timeout(&mut self, duration: Duration) {
66
        #[cfg(loom)]
67
        CURRENT_THREAD_PARK_COUNT.with(|count| count.fetch_add(1, SeqCst));
68
0
        self.inner.park_timeout(duration);
69
0
    }
70
71
0
    pub(crate) fn shutdown(&mut self) {
72
0
        self.inner.shutdown();
73
0
    }
74
}
75
76
// ==== impl Inner ====
77
78
impl Inner {
79
1.28M
    fn park(&self) {
80
        // If we were previously notified then we consume this notification and
81
        // return quickly.
82
1.28M
        if self
83
1.28M
            .state
84
1.28M
            .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst)
85
1.28M
            .is_ok()
86
        {
87
1.26M
            return;
88
17.5k
        }
89
90
        // Otherwise we need to coordinate going to sleep
91
17.5k
        let mut m = self.mutex.lock();
92
93
17.5k
        match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
94
17.5k
            Ok(_) => {}
95
            Err(NOTIFIED) => {
96
                // We must read here, even though we know it will be `NOTIFIED`.
97
                // This is because `unpark` may have been called again since we read
98
                // `NOTIFIED` in the `compare_exchange` above. We must perform an
99
                // acquire operation that synchronizes with that `unpark` to observe
100
                // any writes it made before the call to unpark. To do that we must
101
                // read from the write it made to `state`.
102
0
                let old = self.state.swap(EMPTY, SeqCst);
103
0
                debug_assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
104
105
0
                return;
106
            }
107
0
            Err(actual) => panic!("inconsistent park state; actual = {actual}"),
108
        }
109
110
        loop {
111
17.5k
            m = self.condvar.wait(m).unwrap();
112
113
17.5k
            if self
114
17.5k
                .state
115
17.5k
                .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst)
116
17.5k
                .is_ok()
117
            {
118
                // got a notification
119
17.5k
                return;
120
0
            }
121
122
            // spurious wakeup, go back to sleep
123
        }
124
1.28M
    }
125
126
    /// Parks the current thread for at most `dur`.
127
0
    fn park_timeout(&self, dur: Duration) {
128
        // Like `park` above we have a fast path for an already-notified thread,
129
        // and afterwards we start coordinating for a sleep. Return quickly.
130
0
        if self
131
0
            .state
132
0
            .compare_exchange(NOTIFIED, EMPTY, SeqCst, SeqCst)
133
0
            .is_ok()
134
        {
135
0
            return;
136
0
        }
137
138
0
        if dur == Duration::from_millis(0) {
139
0
            return;
140
0
        }
141
142
0
        let m = self.mutex.lock();
143
144
0
        match self.state.compare_exchange(EMPTY, PARKED, SeqCst, SeqCst) {
145
0
            Ok(_) => {}
146
            Err(NOTIFIED) => {
147
                // We must read again here, see `park`.
148
0
                let old = self.state.swap(EMPTY, SeqCst);
149
0
                debug_assert_eq!(old, NOTIFIED, "park state changed unexpectedly");
150
151
0
                return;
152
            }
153
0
            Err(actual) => panic!("inconsistent park_timeout state; actual = {actual}"),
154
        }
155
156
        #[cfg(not(all(target_family = "wasm", not(target_feature = "atomics"))))]
157
        // Wait with a timeout, and if we spuriously wake up or otherwise wake up
158
        // from a notification, we just want to unconditionally set the state back to
159
        // empty, either consuming a notification or un-flagging ourselves as
160
        // parked.
161
0
        let (_m, _result) = self.condvar.wait_timeout(m, dur).unwrap();
162
163
        #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
164
        // Wasm without atomics doesn't have threads, so just sleep.
165
        {
166
            let _m = m;
167
            std::thread::sleep(dur);
168
        }
169
170
0
        match self.state.swap(EMPTY, SeqCst) {
171
0
            NOTIFIED => {} // got a notification, hurray!
172
0
            PARKED => {}   // no notification, alas
173
0
            n => panic!("inconsistent park_timeout state: {n}"),
174
        }
175
0
    }
176
177
1.76M
    fn unpark(&self) {
178
        // To ensure the unparked thread will observe any writes we made before
179
        // this call, we must perform a release operation that `park` can
180
        // synchronize with. To do that we must write `NOTIFIED` even if `state`
181
        // is already `NOTIFIED`. That is why this must be a swap rather than a
182
        // compare-and-swap that returns if it reads `NOTIFIED` on failure.
183
1.76M
        match self.state.swap(NOTIFIED, SeqCst) {
184
1.26M
            EMPTY => return,    // no one was waiting
185
484k
            NOTIFIED => return, // already unparked
186
17.5k
            PARKED => {}        // gotta go wake someone up
187
0
            _ => panic!("inconsistent state in unpark"),
188
        }
189
190
        // There is a period between when the parked thread sets `state` to
191
        // `PARKED` (or last checked `state` in the case of a spurious wake
192
        // up) and when it actually waits on `cvar`. If we were to notify
193
        // during this period it would be ignored and then when the parked
194
        // thread went to sleep it would never wake up. Fortunately, it has
195
        // `lock` locked at this stage so we can acquire `lock` to wait until
196
        // it is ready to receive the notification.
197
        //
198
        // Releasing `lock` before the call to `notify_one` means that when the
199
        // parked thread wakes it doesn't get woken only to have to wait for us
200
        // to release `lock`.
201
17.5k
        drop(self.mutex.lock());
202
203
17.5k
        self.condvar.notify_one();
204
1.76M
    }
205
206
0
    fn shutdown(&self) {
207
0
        self.condvar.notify_all();
208
0
    }
209
}
210
211
impl Default for ParkThread {
212
0
    fn default() -> Self {
213
0
        Self::new()
214
0
    }
215
}
216
217
// ===== impl UnparkThread =====
218
219
impl UnparkThread {
220
0
    pub(crate) fn unpark(&self) {
221
0
        self.inner.unpark();
222
0
    }
223
}
224
225
use crate::loom::thread::AccessError;
226
use std::future::Future;
227
use std::marker::PhantomData;
228
use std::rc::Rc;
229
use std::task::{RawWaker, RawWakerVTable, Waker};
230
231
/// Blocks the current thread using a condition variable.
232
#[derive(Debug)]
233
pub(crate) struct CachedParkThread {
234
    _anchor: PhantomData<Rc<()>>,
235
}
236
237
impl CachedParkThread {
238
    /// Creates a new `ParkThread` handle for the current thread.
239
    ///
240
    /// This type cannot be moved to other threads, so it should be created on
241
    /// the thread that the caller intends to park.
242
35.1k
    pub(crate) fn new() -> CachedParkThread {
243
35.1k
        CachedParkThread {
244
35.1k
            _anchor: PhantomData,
245
35.1k
        }
246
35.1k
    }
247
248
35.1k
    pub(crate) fn waker(&self) -> Result<Waker, AccessError> {
249
35.1k
        self.unpark().map(UnparkThread::into_waker)
250
35.1k
    }
251
252
35.1k
    fn unpark(&self) -> Result<UnparkThread, AccessError> {
253
35.1k
        self.with_current(ParkThread::unpark)
254
35.1k
    }
255
256
1.28M
    pub(crate) fn park(&mut self) {
257
1.28M
        self.with_current(|park_thread| park_thread.inner.park())
258
1.28M
            .unwrap();
259
1.28M
    }
260
261
0
    pub(crate) fn park_timeout(&mut self, duration: Duration) {
262
0
        self.with_current(|park_thread| park_thread.inner.park_timeout(duration))
263
0
            .unwrap();
264
0
    }
265
266
    /// Gets a reference to the `ParkThread` handle for this thread.
267
1.31M
    fn with_current<F, R>(&self, f: F) -> Result<R, AccessError>
268
1.31M
    where
269
1.31M
        F: FnOnce(&ParkThread) -> R,
270
    {
271
1.31M
        CURRENT_PARKER.try_with(|inner| f(inner))
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::CachedParkThread>::park_timeout::{closure#0}, ()>::{closure#0}
<tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::CachedParkThread>::park::{closure#0}, ()>::{closure#0}
Line
Count
Source
271
1.28M
        CURRENT_PARKER.try_with(|inner| f(inner))
<tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::ParkThread>::unpark, tokio::runtime::park::UnparkThread>::{closure#0}
Line
Count
Source
271
35.1k
        CURRENT_PARKER.try_with(|inner| f(inner))
272
1.31M
    }
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::CachedParkThread>::park_timeout::{closure#0}, ()>
<tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::CachedParkThread>::park::{closure#0}, ()>
Line
Count
Source
267
1.28M
    fn with_current<F, R>(&self, f: F) -> Result<R, AccessError>
268
1.28M
    where
269
1.28M
        F: FnOnce(&ParkThread) -> R,
270
    {
271
1.28M
        CURRENT_PARKER.try_with(|inner| f(inner))
272
1.28M
    }
<tokio::runtime::park::CachedParkThread>::with_current::<<tokio::runtime::park::ParkThread>::unpark, tokio::runtime::park::UnparkThread>
Line
Count
Source
267
35.1k
    fn with_current<F, R>(&self, f: F) -> Result<R, AccessError>
268
35.1k
    where
269
35.1k
        F: FnOnce(&ParkThread) -> R,
270
    {
271
35.1k
        CURRENT_PARKER.try_with(|inner| f(inner))
272
35.1k
    }
273
274
35.1k
    pub(crate) fn block_on<F: Future>(&mut self, f: F) -> Result<F::Output, AccessError> {
275
        use std::task::Context;
276
        use std::task::Poll::Ready;
277
278
35.1k
        let waker = self.waker()?;
279
35.1k
        let mut cx = Context::from_waker(&waker);
280
281
35.1k
        pin!(f);
282
283
        loop {
284
1.31M
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
<tokio::runtime::park::CachedParkThread>::block_on::<&mut tokio::sync::oneshot::Receiver<()>>::{closure#0}
Line
Count
Source
284
38.5k
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::pin::Pin<alloc::boxed::Box<fuzz_client::fuzz_entry::{closure#0}>>>::{closure#0}
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<core::pin::Pin<alloc::boxed::Box<fuzz_client::fuzz_entry::{closure#0}>>>::{closure#0}::{closure#0}>>::{closure#0}
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<fuzz_client::fuzz_entry::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}
<tokio::runtime::park::CachedParkThread>::block_on::<fuzz_client::fuzz_entry::{closure#0}>::{closure#0}
Line
Count
Source
284
4.78k
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::pin::Pin<alloc::boxed::Box<fuzz_e2e::run::{closure#0}>>>::{closure#0}
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<core::pin::Pin<alloc::boxed::Box<fuzz_e2e::run::{closure#0}>>>::{closure#0}::{closure#0}>>::{closure#0}
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<fuzz_e2e::run::{closure#0}>::{closure#0}::{closure#0}>>::{closure#0}
<tokio::runtime::park::CachedParkThread>::block_on::<fuzz_e2e::run::{closure#0}>::{closure#0}
Line
Count
Source
284
1.27M
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
285
35.1k
                return Ok(v);
286
1.28M
            }
287
288
1.28M
            self.park();
289
        }
290
35.1k
    }
<tokio::runtime::park::CachedParkThread>::block_on::<&mut tokio::sync::oneshot::Receiver<()>>
Line
Count
Source
274
17.5k
    pub(crate) fn block_on<F: Future>(&mut self, f: F) -> Result<F::Output, AccessError> {
275
        use std::task::Context;
276
        use std::task::Poll::Ready;
277
278
17.5k
        let waker = self.waker()?;
279
17.5k
        let mut cx = Context::from_waker(&waker);
280
281
17.5k
        pin!(f);
282
283
        loop {
284
38.5k
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
285
17.5k
                return Ok(v);
286
21.0k
            }
287
288
21.0k
            self.park();
289
        }
290
17.5k
    }
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::pin::Pin<alloc::boxed::Box<fuzz_client::fuzz_entry::{closure#0}>>>
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<core::pin::Pin<alloc::boxed::Box<fuzz_client::fuzz_entry::{closure#0}>>>::{closure#0}::{closure#0}>>
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<fuzz_client::fuzz_entry::{closure#0}>::{closure#0}::{closure#0}>>
<tokio::runtime::park::CachedParkThread>::block_on::<fuzz_client::fuzz_entry::{closure#0}>
Line
Count
Source
274
4.78k
    pub(crate) fn block_on<F: Future>(&mut self, f: F) -> Result<F::Output, AccessError> {
275
        use std::task::Context;
276
        use std::task::Poll::Ready;
277
278
4.78k
        let waker = self.waker()?;
279
4.78k
        let mut cx = Context::from_waker(&waker);
280
281
4.78k
        pin!(f);
282
283
        loop {
284
4.78k
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
285
4.78k
                return Ok(v);
286
0
            }
287
288
0
            self.park();
289
        }
290
4.78k
    }
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::pin::Pin<alloc::boxed::Box<fuzz_e2e::run::{closure#0}>>>
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<core::pin::Pin<alloc::boxed::Box<fuzz_e2e::run::{closure#0}>>>::{closure#0}::{closure#0}>>
Unexecuted instantiation: <tokio::runtime::park::CachedParkThread>::block_on::<core::future::poll_fn::PollFn<<tokio::runtime::scheduler::current_thread::CurrentThread>::block_on<fuzz_e2e::run::{closure#0}>::{closure#0}::{closure#0}>>
<tokio::runtime::park::CachedParkThread>::block_on::<fuzz_e2e::run::{closure#0}>
Line
Count
Source
274
12.7k
    pub(crate) fn block_on<F: Future>(&mut self, f: F) -> Result<F::Output, AccessError> {
275
        use std::task::Context;
276
        use std::task::Poll::Ready;
277
278
12.7k
        let waker = self.waker()?;
279
12.7k
        let mut cx = Context::from_waker(&waker);
280
281
12.7k
        pin!(f);
282
283
        loop {
284
1.27M
            if let Ready(v) = crate::task::coop::budget(|| f.as_mut().poll(&mut cx)) {
285
12.7k
                return Ok(v);
286
1.25M
            }
287
288
1.25M
            self.park();
289
        }
290
12.7k
    }
291
}
292
293
impl UnparkThread {
294
35.1k
    pub(crate) fn into_waker(self) -> Waker {
295
        unsafe {
296
35.1k
            let raw = unparker_to_raw_waker(self.inner);
297
35.1k
            Waker::from_raw(raw)
298
        }
299
35.1k
    }
300
}
301
302
impl Inner {
303
    #[allow(clippy::wrong_self_convention)]
304
2.51M
    fn into_raw(this: Arc<Inner>) -> *const () {
305
2.51M
        Arc::into_raw(this) as *const ()
306
2.51M
    }
307
308
    /// # Safety
309
    ///
310
    /// The pointer must have been created by [`Self::into_raw`].
311
4.98M
    unsafe fn from_raw(ptr: *const ()) -> Arc<Inner> {
312
4.98M
        unsafe { Arc::from_raw(ptr as *const Inner) }
313
4.98M
    }
314
}
315
316
// TODO: Is this really an unsafe function?
317
2.51M
unsafe fn unparker_to_raw_waker(unparker: Arc<Inner>) -> RawWaker {
318
2.51M
    RawWaker::new(
319
2.51M
        Inner::into_raw(unparker),
320
2.51M
        &RawWakerVTable::new(clone, wake, wake_by_ref, drop_waker),
321
    )
322
2.51M
}
323
324
/// # Safety
325
///
326
/// The pointer must have been created by [`Inner::into_raw`].
327
2.47M
unsafe fn clone(raw: *const ()) -> RawWaker {
328
2.47M
    unsafe {
329
2.47M
        Arc::increment_strong_count(raw as *const Inner);
330
2.47M
    }
331
2.47M
    unsafe { unparker_to_raw_waker(Inner::from_raw(raw)) }
332
2.47M
}
333
334
/// # Safety
335
///
336
/// The pointer must have been created by [`Inner::into_raw`].
337
767k
unsafe fn drop_waker(raw: *const ()) {
338
767k
    drop(unsafe { Inner::from_raw(raw) });
339
767k
}
340
341
/// # Safety
342
///
343
/// The pointer must have been created by [`Inner::into_raw`].
344
1.74M
unsafe fn wake(raw: *const ()) {
345
1.74M
    let unparker = unsafe { Inner::from_raw(raw) };
346
1.74M
    unparker.unpark();
347
1.74M
}
348
349
/// # Safety
350
///
351
/// The pointer must have been created by [`Inner::into_raw`].
352
21.1k
unsafe fn wake_by_ref(raw: *const ()) {
353
21.1k
    let raw = raw as *const Inner;
354
21.1k
    unsafe {
355
21.1k
        (*raw).unpark();
356
21.1k
    }
357
21.1k
}
358
359
#[cfg(loom)]
360
pub(crate) fn current_thread_park_count() -> usize {
361
    CURRENT_THREAD_PARK_COUNT.with(|count| count.load(SeqCst))
362
}