Debian Codegraph @

third_party/rust/tokio/src/runtime/tests/loom_multi_thread_alt.rs

raw
1 #![cfg(tokio_unstable)]
2
3 mod queue;
4 mod shutdown;
5 mod yield_now;
6
7 /// Full runtime loom tests. These are heavy tests and take significant time to
8 /// run on CI.
9 ///
10 /// Use `LOOM_MAX_PREEMPTIONS=1` to do a "quick" run as a smoke test.
11 ///
12 /// In order to speed up the C
13 use crate::future::poll_fn;
14 use crate::runtime::tests::loom_oneshot as oneshot;
15 use crate::runtime::{self, Runtime};
16 use crate::{spawn, task};
17 use tokio_test::assert_ok;
18
19 use loom::sync::atomic::{AtomicBool, AtomicUsize};
20 use loom::sync::Arc;
21
22 use pin_project_lite::pin_project;
23 use std::future::Future;
24 use std::pin::Pin;
25 use std::sync::atomic::Ordering::{Relaxed, SeqCst};
26 use std::task::{Context, Poll};
27
28 mod atomic_take {
29 use loom::sync::atomic::AtomicBool;
30 use std::mem::MaybeUninit;
31 use std::sync::atomic::Ordering::SeqCst;
32
33 pub(super) struct AtomicTake<T> {
34 inner: MaybeUninit<T>,
35 taken: AtomicBool,
36 }
37
38 impl<T> AtomicTake<T> {
39 pub(super) fn new(value: T) -> Self {
40 Self {
41 inner: MaybeUninit::new(value),
42 taken: AtomicBool::new(false),
43 }
44 }
45
46 pub(super) fn take(&self) -> Option<T> {
47 // safety: Only one thread will see the boolean change from false
48 // to true, so that thread is able to take the value.
49 match self.taken.fetch_or(true, SeqCst) {
50 false => unsafe { Some(std::ptr::read(self.inner.as_ptr())) },
51 true => None,
52 }
53 }
54 }
55
56 impl<T> Drop for AtomicTake<T> {
57 fn drop(&mut self) {
58 drop(self.take());
59 }
60 }
61 }
62
63 #[derive(Clone)]
64 struct AtomicOneshot<T> {
65 value: std::sync::Arc<atomic_take::AtomicTake<oneshot::Sender<T>>>,
66 }
67 impl<T> AtomicOneshot<T> {
68 fn new(sender: oneshot::Sender<T>) -> Self {
69 Self {
70 value: std::sync::Arc::new(atomic_take::AtomicTake::new(sender)),
71 }
72 }
73
74 fn assert_send(&self, value: T) {
75 self.value.take().unwrap().send(value);
76 }
77 }
78
79 /// Tests are divided into groups to make the runs faster on CI.
80 mod group_a {
81 use super::*;
82
83 #[test]
84 fn racy_shutdown() {
85 loom::model(|| {
86 let pool = mk_pool(1);
87
88 // here's the case we want to exercise:
89 //
90 // a worker that still has tasks in its local queue gets sent to the blocking pool (due to
91 // block_in_place). the blocking pool is shut down, so drops the worker. the worker's
92 // shutdown method never gets run.
93 //
94 // we do this by spawning two tasks on one worker, the first of which does block_in_place,
95 // and then immediately drop the pool.
96
97 pool.spawn(track(async {
98 crate::task::block_in_place(|| {});
99 }));
100 pool.spawn(track(async {}));
101 drop(pool);
102 });
103 }
104
105 #[test]
106 fn pool_multi_spawn() {
107 loom::model(|| {
108 let pool = mk_pool(2);
109 let c1 = Arc::new(AtomicUsize::new(0));
110
111 let (tx, rx) = oneshot::channel();
112 let tx1 = AtomicOneshot::new(tx);
113
114 // Spawn a task
115 let c2 = c1.clone();
116 let tx2 = tx1.clone();
117 pool.spawn(track(async move {
118 spawn(track(async move {
119 if 1 == c1.fetch_add(1, Relaxed) {
120 tx1.assert_send(());
121 }
122 }));
123 }));
124
125 // Spawn a second task
126 pool.spawn(track(async move {
127 spawn(track(async move {
128 if 1 == c2.fetch_add(1, Relaxed) {
129 tx2.assert_send(());
130 }
131 }));
132 }));
133
134 rx.recv();
135 });
136 }
137
138 fn only_blocking_inner(first_pending: bool) {
139 loom::model(move || {
140 let pool = mk_pool(1);
141 let (block_tx, block_rx) = oneshot::channel();
142
143 pool.spawn(track(async move {
144 crate::task::block_in_place(move || {
145 block_tx.send(());
146 });
147 if first_pending {
148 task::yield_now().await
149 }
150 }));
151
152 block_rx.recv();
153 drop(pool);
154 });
155 }
156
157 #[test]
158 fn only_blocking_without_pending() {
159 only_blocking_inner(false)
160 }
161
162 #[test]
163 fn only_blocking_with_pending() {
164 only_blocking_inner(true)
165 }
166 }
167
168 mod group_b {
169 use super::*;
170
171 fn blocking_and_regular_inner(first_pending: bool) {
172 const NUM: usize = 3;
173 loom::model(move || {
174 let pool = mk_pool(1);
175 let cnt = Arc::new(AtomicUsize::new(0));
176
177 let (block_tx, block_rx) = oneshot::channel();
178 let (done_tx, done_rx) = oneshot::channel();
179 let done_tx = AtomicOneshot::new(done_tx);
180
181 pool.spawn(track(async move {
182 crate::task::block_in_place(move || {
183 block_tx.send(());
184 });
185 if first_pending {
186 task::yield_now().await
187 }
188 }));
189
190 for _ in 0..NUM {
191 let cnt = cnt.clone();
192 let done_tx = done_tx.clone();
193
194 pool.spawn(track(async move {
195 if NUM == cnt.fetch_add(1, Relaxed) + 1 {
196 done_tx.assert_send(());
197 }
198 }));
199 }
200
201 done_rx.recv();
202 block_rx.recv();
203
204 drop(pool);
205 });
206 }
207
208 #[test]
209 #[ignore] // TODO: uncomment
210 fn blocking_and_regular_without_pending() {
211 blocking_and_regular_inner(false);
212 }
213
214 #[test]
215 fn blocking_and_regular_with_pending() {
216 blocking_and_regular_inner(true);
217 }
218
219 #[test]
220 fn join_output() {
221 loom::model(|| {
222 let rt = mk_pool(1);
223
224 rt.block_on(async {
225 let t = crate::spawn(track(async { "hello" }));
226
227 let out = assert_ok!(t.await);
228 assert_eq!("hello", out.into_inner());
229 });
230 });
231 }
232
233 #[test]
234 fn poll_drop_handle_then_drop() {
235 loom::model(|| {
236 let rt = mk_pool(1);
237
238 rt.block_on(async move {
239 let mut t = crate::spawn(track(async { "hello" }));
240
241 poll_fn(|cx| {
242 let _ = Pin::new(&mut t).poll(cx);
243 Poll::Ready(())
244 })
245 .await;
246 });
247 })
248 }
249
250 #[test]
251 fn complete_block_on_under_load() {
252 loom::model(|| {
253 let pool = mk_pool(1);
254
255 pool.block_on(async {
256 // Trigger a re-schedule
257 crate::spawn(track(async {
258 for _ in 0..2 {
259 task::yield_now().await;
260 }
261 }));
262
263 gated2(true).await
264 });
265 });
266 }
267
268 #[test]
269 fn shutdown_with_notification() {
270 use crate::sync::oneshot;
271
272 loom::model(|| {
273 let rt = mk_pool(2);
274 let (done_tx, done_rx) = oneshot::channel::<()>();
275
276 rt.spawn(track(async move {
277 let (tx, rx) = oneshot::channel::<()>();
278
279 crate::spawn(async move {
280 crate::task::spawn_blocking(move || {
281 let _ = tx.send(());
282 });
283
284 let _ = done_rx.await;
285 });
286
287 let _ = rx.await;
288
289 let _ = done_tx.send(());
290 }));
291 });
292 }
293 }
294
295 mod group_c {
296 use super::*;
297
298 #[test]
299 fn pool_shutdown() {
300 loom::model(|| {
301 let pool = mk_pool(2);
302
303 pool.spawn(track(async move {
304 gated2(true).await;
305 }));
306
307 pool.spawn(track(async move {
308 gated2(false).await;
309 }));
310
311 drop(pool);
312 });
313 }
314
315 #[test]
316 fn fill_local_queue() {
317 const NUM_SPAWNS: usize = 3;
318 loom::model(|| {
319 // using std versions here as it is just to control shutdown.
320 let cnt = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
321 let (tx, rx) = oneshot::channel();
322 let tx = AtomicOneshot::new(tx);
323
324 let pool = runtime::Builder::new_multi_thread_alt()
325 .worker_threads(2)
326 // Set the intervals to avoid tuning logic
327 .global_queue_interval(61)
328 .local_queue_capacity(1)
329 .build()
330 .unwrap();
331
332 for _ in 0..NUM_SPAWNS {
333 let cnt = cnt.clone();
334 let tx = tx.clone();
335 pool.spawn(track(async move {
336 if NUM_SPAWNS == 1 + cnt.fetch_add(1, Relaxed) {
337 tx.assert_send(());
338 }
339 }));
340 }
341
342 rx.recv();
343 });
344 }
345
346 // This tests a very specific case that happened when a worker has no more
347 // available work to process because a peer is in the process of stealing
348 // (but does not finish stealing), and the worker happens to find more work
349 // from the injection queue *right* before parking.
350 #[test]
351 fn pool_concurrent_park_with_steal_with_inject() {
352 const DEPTH: usize = 4;
353
354 let mut model = loom::model::Builder::new();
355 model.expect_explicit_explore = true;
356 model.preemption_bound = Some(3);
357
358 model.check(|| {
359 let pool = runtime::Builder::new_multi_thread_alt()
360 .worker_threads(2)
361 // Set the intervals to avoid tuning logic
362 .global_queue_interval(61)
363 .local_queue_capacity(DEPTH)
364 .build()
365 .unwrap();
366
367 // Use std types to avoid adding backtracking.
368 type Flag = std::sync::Arc<std::sync::atomic::AtomicIsize>;
369 let flag: Flag = Default::default();
370 let flag1 = flag.clone();
371
372 let (tx1, rx1) = oneshot::channel();
373
374 async fn task(expect: isize, flag: Flag) {
375 if expect == flag.load(Relaxed) {
376 flag.store(expect + 1, Relaxed);
377 } else {
378 flag.store(-1, Relaxed);
379 loom::skip_branch();
380 }
381 }
382
383 pool.spawn(track(async move {
384 let flag = flag1;
385 // First 2 spawned task should be stolen
386 crate::spawn(task(1, flag.clone()));
387 crate::spawn(task(2, flag.clone()));
388 crate::spawn(async move {
389 task(0, flag.clone()).await;
390 tx1.send(());
391 });
392
393 // One to fill the LIFO slot
394 crate::spawn(async move {});
395
396 loom::explore();
397 }));
398
399 rx1.recv();
400
401 if 1 == flag.load(Relaxed) {
402 loom::stop_exploring();
403
404 let (tx3, rx3) = oneshot::channel();
405 pool.spawn(async move {
406 loom::skip_branch();
407 tx3.send(());
408 });
409
410 pool.spawn(async {});
411 pool.spawn(async {});
412
413 loom::explore();
414
415 rx3.recv();
416 } else {
417 loom::skip_branch();
418 }
419 });
420 }
421 }
422
423 mod group_d {
424 use super::*;
425
426 #[test]
427 fn pool_multi_notify() {
428 loom::model(|| {
429 let pool = mk_pool(2);
430
431 let c1 = Arc::new(AtomicUsize::new(0));
432
433 let (done_tx, done_rx) = oneshot::channel();
434 let done_tx1 = AtomicOneshot::new(done_tx);
435 let done_tx2 = done_tx1.clone();
436
437 // Spawn a task
438 let c2 = c1.clone();
439 pool.spawn(track(async move {
440 multi_gated().await;
441
442 if 1 == c1.fetch_add(1, Relaxed) {
443 done_tx1.assert_send(());
444 }
445 }));
446
447 // Spawn a second task
448 pool.spawn(track(async move {
449 multi_gated().await;
450
451 if 1 == c2.fetch_add(1, Relaxed) {
452 done_tx2.assert_send(());
453 }
454 }));
455
456 done_rx.recv();
457 });
458 }
459 }
460
461 fn mk_pool(num_threads: usize) -> Runtime {
462 runtime::Builder::new_multi_thread_alt()
463 .worker_threads(num_threads)
464 // Set the intervals to avoid tuning logic
465 .global_queue_interval(61)
466 .build()
467 .unwrap()
468 }
469
470 fn gated2(thread: bool) -> impl Future<Output = &'static str> {
471 use loom::thread;
472 use std::sync::Arc;
473
474 let gate = Arc::new(AtomicBool::new(false));
475 let mut fired = false;
476
477 poll_fn(move |cx| {
478 if !fired {
479 let gate = gate.clone();
480 let waker = cx.waker().clone();
481
482 if thread {
483 thread::spawn(move || {
484 gate.store(true, SeqCst);
485 waker.wake_by_ref();
486 });
487 } else {
488 spawn(track(async move {
489 gate.store(true, SeqCst);
490 waker.wake_by_ref();
491 }));
492 }
493
494 fired = true;
495
496 return Poll::Pending;
497 }
498
499 if gate.load(SeqCst) {
500 Poll::Ready("hello world")
501 } else {
502 Poll::Pending
503 }
504 })
505 }
506
507 async fn multi_gated() {
508 struct Gate {
509 waker: loom::future::AtomicWaker,
510 count: AtomicUsize,
511 }
512
513 let gate = Arc::new(Gate {
514 waker: loom::future::AtomicWaker::new(),
515 count: AtomicUsize::new(0),
516 });
517
518 {
519 let gate = gate.clone();
520 spawn(track(async move {
521 for i in 1..3 {
522 gate.count.store(i, SeqCst);
523 gate.waker.wake();
524 }
525 }));
526 }
527
528 poll_fn(move |cx| {
529 gate.waker.register_by_ref(cx.waker());
530 if gate.count.load(SeqCst) < 2 {
531 Poll::Pending
532 } else {
533 Poll::Ready(())
534 }
535 })
536 .await;
537 }
538
539 fn track<T: Future>(f: T) -> Track<T> {
540 Track {
541 inner: f,
542 arc: Arc::new(()),
543 }
544 }
545
546 pin_project! {
547 struct Track<T> {
548 #[pin]
549 inner: T,
550 // Arc is used to hook into loom's leak tracking.
551 arc: Arc<()>,
552 }
553 }
554
555 impl<T> Track<T> {
556 fn into_inner(self) -> T {
557 self.inner
558 }
559 }
560
561 impl<T: Future> Future for Track<T> {
562 type Output = Track<T::Output>;
563
564 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
565 let me = self.project();
566
567 Poll::Ready(Track {
568 inner: ready!(me.inner.poll(cx)),
569 arc: me.arc.clone(),
570 })
571 }
572 }