Debian Codegraph @

third_party/rust/tokio/tests/rt_threaded_alt.rs

raw
1 #![allow(unknown_lints, unexpected_cfgs)]
2 #![warn(rust_2018_idioms)]
3 #![cfg(all(feature = "full", not(target_os = "wasi")))]
4 #![cfg(tokio_unstable)]
5
6 use tokio::io::{AsyncReadExt, AsyncWriteExt};
7 use tokio::net::{TcpListener, TcpStream};
8 use tokio::runtime;
9 use tokio::sync::oneshot;
10 use tokio_test::{assert_err, assert_ok};
11
12 use futures::future::poll_fn;
13 use std::future::Future;
14 use std::pin::Pin;
15 use std::sync::atomic::AtomicUsize;
16 use std::sync::atomic::Ordering::Relaxed;
17 use std::sync::{mpsc, Arc, Mutex};
18 use std::task::{Context, Poll, Waker};
19
20 macro_rules! cfg_metrics {
21 ($($t:tt)*) => {
22 #[cfg(all(tokio_unstable, target_has_atomic = "64"))]
23 {
24 $( $t )*
25 }
26 }
27 }
28
29 #[test]
30 fn single_thread() {
31 // No panic when starting a runtime w/ a single thread
32 let _ = runtime::Builder::new_multi_thread_alt()
33 .enable_all()
34 .worker_threads(1)
35 .build()
36 .unwrap();
37 }
38
39 #[test]
40 #[ignore] // https://github.com/tokio-rs/tokio/issues/5995
41 fn many_oneshot_futures() {
42 // used for notifying the main thread
43 const NUM: usize = 1_000;
44
45 for _ in 0..5 {
46 let (tx, rx) = mpsc::channel();
47
48 let rt = rt();
49 let cnt = Arc::new(AtomicUsize::new(0));
50
51 for _ in 0..NUM {
52 let cnt = cnt.clone();
53 let tx = tx.clone();
54
55 rt.spawn(async move {
56 let num = cnt.fetch_add(1, Relaxed) + 1;
57
58 if num == NUM {
59 tx.send(()).unwrap();
60 }
61 });
62 }
63
64 rx.recv().unwrap();
65
66 // Wait for the pool to shutdown
67 drop(rt);
68 }
69 }
70
71 #[test]
72 fn spawn_two() {
73 let rt = rt();
74
75 let out = rt.block_on(async {
76 let (tx, rx) = oneshot::channel();
77
78 tokio::spawn(async move {
79 tokio::spawn(async move {
80 tx.send("ZOMG").unwrap();
81 });
82 });
83
84 assert_ok!(rx.await)
85 });
86
87 assert_eq!(out, "ZOMG");
88
89 cfg_metrics! {
90 let metrics = rt.metrics();
91 drop(rt);
92 assert_eq!(1, metrics.remote_schedule_count());
93
94 let mut local = 0;
95 for i in 0..metrics.num_workers() {
96 local += metrics.worker_local_schedule_count(i);
97 }
98
99 assert_eq!(1, local);
100 }
101 }
102
103 #[test]
104 fn many_multishot_futures() {
105 const CHAIN: usize = 200;
106 const CYCLES: usize = 5;
107 const TRACKS: usize = 50;
108
109 for _ in 0..50 {
110 let rt = rt();
111 let mut start_txs = Vec::with_capacity(TRACKS);
112 let mut final_rxs = Vec::with_capacity(TRACKS);
113
114 for _ in 0..TRACKS {
115 let (start_tx, mut chain_rx) = tokio::sync::mpsc::channel(10);
116
117 for _ in 0..CHAIN {
118 let (next_tx, next_rx) = tokio::sync::mpsc::channel(10);
119
120 // Forward all the messages
121 rt.spawn(async move {
122 while let Some(v) = chain_rx.recv().await {
123 next_tx.send(v).await.unwrap();
124 }
125 });
126
127 chain_rx = next_rx;
128 }
129
130 // This final task cycles if needed
131 let (final_tx, final_rx) = tokio::sync::mpsc::channel(10);
132 let cycle_tx = start_tx.clone();
133 let mut rem = CYCLES;
134
135 rt.spawn(async move {
136 for _ in 0..CYCLES {
137 let msg = chain_rx.recv().await.unwrap();
138
139 rem -= 1;
140
141 if rem == 0 {
142 final_tx.send(msg).await.unwrap();
143 } else {
144 cycle_tx.send(msg).await.unwrap();
145 }
146 }
147 });
148
149 start_txs.push(start_tx);
150 final_rxs.push(final_rx);
151 }
152
153 {
154 rt.block_on(async move {
155 for start_tx in start_txs {
156 start_tx.send("ping").await.unwrap();
157 }
158
159 for mut final_rx in final_rxs {
160 final_rx.recv().await.unwrap();
161 }
162 });
163 }
164 }
165 }
166
167 #[test]
168 fn lifo_slot_budget() {
169 async fn my_fn() {
170 spawn_another();
171 }
172
173 fn spawn_another() {
174 tokio::spawn(my_fn());
175 }
176
177 let rt = runtime::Builder::new_multi_thread_alt()
178 .enable_all()
179 .worker_threads(1)
180 .build()
181 .unwrap();
182
183 let (send, recv) = oneshot::channel();
184
185 rt.spawn(async move {
186 tokio::spawn(my_fn());
187 let _ = send.send(());
188 });
189
190 let _ = rt.block_on(recv);
191 }
192
193 #[test]
194 fn spawn_shutdown() {
195 let rt = rt();
196 let (tx, rx) = mpsc::channel();
197
198 rt.block_on(async {
199 tokio::spawn(client_server(tx.clone()));
200 });
201
202 // Use spawner
203 rt.spawn(client_server(tx));
204
205 assert_ok!(rx.recv());
206 assert_ok!(rx.recv());
207
208 drop(rt);
209 assert_err!(rx.try_recv());
210 }
211
212 async fn client_server(tx: mpsc::Sender<()>) {
213 let server = assert_ok!(TcpListener::bind("127.0.0.1:0").await);
214
215 // Get the assigned address
216 let addr = assert_ok!(server.local_addr());
217
218 // Spawn the server
219 tokio::spawn(async move {
220 // Accept a socket
221 let (mut socket, _) = server.accept().await.unwrap();
222
223 // Write some data
224 socket.write_all(b"hello").await.unwrap();
225 });
226
227 let mut client = TcpStream::connect(&addr).await.unwrap();
228
229 let mut buf = vec![];
230 client.read_to_end(&mut buf).await.unwrap();
231
232 assert_eq!(buf, b"hello");
233 tx.send(()).unwrap();
234 }
235
236 #[test]
237 fn drop_threadpool_drops_futures() {
238 for _ in 0..1_000 {
239 let num_inc = Arc::new(AtomicUsize::new(0));
240 let num_dec = Arc::new(AtomicUsize::new(0));
241 let num_drop = Arc::new(AtomicUsize::new(0));
242
243 struct Never(Arc<AtomicUsize>);
244
245 impl Future for Never {
246 type Output = ();
247
248 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
249 Poll::Pending
250 }
251 }
252
253 impl Drop for Never {
254 fn drop(&mut self) {
255 self.0.fetch_add(1, Relaxed);
256 }
257 }
258
259 let a = num_inc.clone();
260 let b = num_dec.clone();
261
262 let rt = runtime::Builder::new_multi_thread_alt()
263 .enable_all()
264 .on_thread_start(move || {
265 a.fetch_add(1, Relaxed);
266 })
267 .on_thread_stop(move || {
268 b.fetch_add(1, Relaxed);
269 })
270 .build()
271 .unwrap();
272
273 rt.spawn(Never(num_drop.clone()));
274
275 // Wait for the pool to shutdown
276 drop(rt);
277
278 // Assert that only a single thread was spawned.
279 let a = num_inc.load(Relaxed);
280 assert!(a >= 1);
281
282 // Assert that all threads shutdown
283 let b = num_dec.load(Relaxed);
284 assert_eq!(a, b);
285
286 // Assert that the future was dropped
287 let c = num_drop.load(Relaxed);
288 assert_eq!(c, 1);
289 }
290 }
291
292 #[test]
293 fn start_stop_callbacks_called() {
294 use std::sync::atomic::{AtomicUsize, Ordering};
295
296 let after_start = Arc::new(AtomicUsize::new(0));
297 let before_stop = Arc::new(AtomicUsize::new(0));
298
299 let after_inner = after_start.clone();
300 let before_inner = before_stop.clone();
301 let rt = tokio::runtime::Builder::new_multi_thread_alt()
302 .enable_all()
303 .on_thread_start(move || {
304 after_inner.clone().fetch_add(1, Ordering::Relaxed);
305 })
306 .on_thread_stop(move || {
307 before_inner.clone().fetch_add(1, Ordering::Relaxed);
308 })
309 .build()
310 .unwrap();
311
312 let (tx, rx) = oneshot::channel();
313
314 rt.spawn(async move {
315 assert_ok!(tx.send(()));
316 });
317
318 assert_ok!(rt.block_on(rx));
319
320 drop(rt);
321
322 assert!(after_start.load(Ordering::Relaxed) > 0);
323 assert!(before_stop.load(Ordering::Relaxed) > 0);
324 }
325
326 #[test]
327 fn blocking_task() {
328 // used for notifying the main thread
329 const NUM: usize = 1_000;
330
331 for _ in 0..10 {
332 let (tx, rx) = mpsc::channel();
333
334 let rt = rt();
335 let cnt = Arc::new(AtomicUsize::new(0));
336
337 // there are four workers in the pool
338 // so, if we run 4 blocking tasks, we know that handoff must have happened
339 let block = Arc::new(std::sync::Barrier::new(5));
340 for _ in 0..4 {
341 let block = block.clone();
342 rt.spawn(async move {
343 tokio::task::block_in_place(move || {
344 block.wait();
345 block.wait();
346 })
347 });
348 }
349 block.wait();
350
351 for _ in 0..NUM {
352 let cnt = cnt.clone();
353 let tx = tx.clone();
354
355 rt.spawn(async move {
356 let num = cnt.fetch_add(1, Relaxed) + 1;
357
358 if num == NUM {
359 tx.send(()).unwrap();
360 }
361 });
362 }
363
364 rx.recv().unwrap();
365
366 // Wait for the pool to shutdown
367 block.wait();
368 }
369 }
370
371 #[test]
372 fn multi_threadpool() {
373 use tokio::sync::oneshot;
374
375 let rt1 = rt();
376 let rt2 = rt();
377
378 let (tx, rx) = oneshot::channel();
379 let (done_tx, done_rx) = mpsc::channel();
380
381 rt2.spawn(async move {
382 rx.await.unwrap();
383 done_tx.send(()).unwrap();
384 });
385
386 rt1.spawn(async move {
387 tx.send(()).unwrap();
388 });
389
390 done_rx.recv().unwrap();
391 }
392
393 // When `block_in_place` returns, it attempts to reclaim the yielded runtime
394 // worker. In this case, the remainder of the task is on the runtime worker and
395 // must take part in the cooperative task budgeting system.
396 //
397 // The test ensures that, when this happens, attempting to consume from a
398 // channel yields occasionally even if there are values ready to receive.
399 #[test]
400 fn coop_and_block_in_place() {
401 let rt = tokio::runtime::Builder::new_multi_thread_alt()
402 // Setting max threads to 1 prevents another thread from claiming the
403 // runtime worker yielded as part of `block_in_place` and guarantees the
404 // same thread will reclaim the worker at the end of the
405 // `block_in_place` call.
406 .max_blocking_threads(1)
407 .build()
408 .unwrap();
409
410 rt.block_on(async move {
411 let (tx, mut rx) = tokio::sync::mpsc::channel(1024);
412
413 // Fill the channel
414 for _ in 0..1024 {
415 tx.send(()).await.unwrap();
416 }
417
418 drop(tx);
419
420 tokio::spawn(async move {
421 // Block in place without doing anything
422 tokio::task::block_in_place(|| {});
423
424 // Receive all the values, this should trigger a `Pending` as the
425 // coop limit will be reached.
426 poll_fn(|cx| {
427 while let Poll::Ready(v) = {
428 tokio::pin! {
429 let fut = rx.recv();
430 }
431
432 Pin::new(&mut fut).poll(cx)
433 } {
434 if v.is_none() {
435 panic!("did not yield");
436 }
437 }
438
439 Poll::Ready(())
440 })
441 .await
442 })
443 .await
444 .unwrap();
445 });
446 }
447
448 #[test]
449 fn yield_after_block_in_place() {
450 let rt = tokio::runtime::Builder::new_multi_thread_alt()
451 .worker_threads(1)
452 .build()
453 .unwrap();
454
455 rt.block_on(async {
456 tokio::spawn(async move {
457 // Block in place then enter a new runtime
458 tokio::task::block_in_place(|| {
459 let rt = tokio::runtime::Builder::new_current_thread()
460 .build()
461 .unwrap();
462
463 rt.block_on(async {});
464 });
465
466 // Yield, then complete
467 tokio::task::yield_now().await;
468 })
469 .await
470 .unwrap()
471 });
472 }
473
474 // Testing this does not panic
475 #[test]
476 fn max_blocking_threads() {
477 let _rt = tokio::runtime::Builder::new_multi_thread_alt()
478 .max_blocking_threads(1)
479 .build()
480 .unwrap();
481 }
482
483 #[test]
484 #[should_panic]
485 fn max_blocking_threads_set_to_zero() {
486 let _rt = tokio::runtime::Builder::new_multi_thread_alt()
487 .max_blocking_threads(0)
488 .build()
489 .unwrap();
490 }
491
492 /// Regression test for #6445.
493 ///
494 /// After #6445, setting `global_queue_interval` to 1 is now technically valid.
495 /// This test confirms that there is no regression in `multi_thread_runtime`
496 /// when global_queue_interval is set to 1.
497 #[test]
498 fn global_queue_interval_set_to_one() {
499 let rt = tokio::runtime::Builder::new_multi_thread_alt()
500 .global_queue_interval(1)
501 .build()
502 .unwrap();
503
504 // Perform a simple work.
505 let cnt = Arc::new(AtomicUsize::new(0));
506 rt.block_on(async {
507 let mut set = tokio::task::JoinSet::new();
508 for _ in 0..10 {
509 let cnt = cnt.clone();
510 set.spawn(async move { cnt.fetch_add(1, Relaxed) });
511 }
512 while let Some(res) = set.join_next().await {
513 res.unwrap();
514 }
515 });
516 assert_eq!(cnt.load(Relaxed), 10);
517 }
518
519 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
520 async fn hang_on_shutdown() {
521 let (sync_tx, sync_rx) = std::sync::mpsc::channel::<()>();
522 tokio::spawn(async move {
523 tokio::task::block_in_place(|| sync_rx.recv().ok());
524 });
525
526 tokio::spawn(async {
527 tokio::time::sleep(std::time::Duration::from_secs(2)).await;
528 drop(sync_tx);
529 });
530 tokio::time::sleep(std::time::Duration::from_secs(1)).await;
531 }
532
533 /// Demonstrates tokio-rs/tokio#3869
534 #[test]
535 fn wake_during_shutdown() {
536 struct Shared {
537 waker: Option<Waker>,
538 }
539
540 struct MyFuture {
541 shared: Arc<Mutex<Shared>>,
542 put_waker: bool,
543 }
544
545 impl MyFuture {
546 fn new() -> (Self, Self) {
547 let shared = Arc::new(Mutex::new(Shared { waker: None }));
548 let f1 = MyFuture {
549 shared: shared.clone(),
550 put_waker: true,
551 };
552 let f2 = MyFuture {
553 shared,
554 put_waker: false,
555 };
556 (f1, f2)
557 }
558 }
559
560 impl Future for MyFuture {
561 type Output = ();
562
563 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
564 let me = Pin::into_inner(self);
565 let mut lock = me.shared.lock().unwrap();
566 if me.put_waker {
567 lock.waker = Some(cx.waker().clone());
568 }
569 Poll::Pending
570 }
571 }
572
573 impl Drop for MyFuture {
574 fn drop(&mut self) {
575 let mut lock = self.shared.lock().unwrap();
576 if !self.put_waker {
577 lock.waker.take().unwrap().wake();
578 }
579 drop(lock);
580 }
581 }
582
583 let rt = tokio::runtime::Builder::new_multi_thread_alt()
584 .worker_threads(1)
585 .enable_all()
586 .build()
587 .unwrap();
588
589 let (f1, f2) = MyFuture::new();
590
591 rt.spawn(f1);
592 rt.spawn(f2);
593
594 rt.block_on(async { tokio::time::sleep(tokio::time::Duration::from_millis(20)).await });
595 }
596
597 #[should_panic]
598 #[tokio::test]
599 async fn test_block_in_place1() {
600 tokio::task::block_in_place(|| {});
601 }
602
603 #[tokio::test(flavor = "multi_thread")]
604 async fn test_block_in_place2() {
605 tokio::task::block_in_place(|| {});
606 }
607
608 #[should_panic]
609 #[tokio::main(flavor = "current_thread")]
610 #[test]
611 async fn test_block_in_place3() {
612 tokio::task::block_in_place(|| {});
613 }
614
615 #[tokio::main]
616 #[test]
617 async fn test_block_in_place4() {
618 tokio::task::block_in_place(|| {});
619 }
620
621 // Testing the tuning logic is tricky as it is inherently timing based, and more
622 // of a heuristic than an exact behavior. This test checks that the interval
623 // changes over time based on load factors. There are no assertions, completion
624 // is sufficient. If there is a regression, this test will hang. In theory, we
625 // could add limits, but that would be likely to fail on CI.
626 #[test]
627 #[cfg(not(tokio_no_tuning_tests))]
628 fn test_tuning() {
629 use std::sync::atomic::AtomicBool;
630 use std::time::Duration;
631
632 let rt = runtime::Builder::new_multi_thread_alt()
633 .worker_threads(1)
634 .build()
635 .unwrap();
636
637 fn iter(flag: Arc<AtomicBool>, counter: Arc<AtomicUsize>, stall: bool) {
638 if flag.load(Relaxed) {
639 if stall {
640 std::thread::sleep(Duration::from_micros(5));
641 }
642
643 counter.fetch_add(1, Relaxed);
644 tokio::spawn(async move { iter(flag, counter, stall) });
645 }
646 }
647
648 let flag = Arc::new(AtomicBool::new(true));
649 let counter = Arc::new(AtomicUsize::new(61));
650 let interval = Arc::new(AtomicUsize::new(61));
651
652 {
653 let flag = flag.clone();
654 let counter = counter.clone();
655 rt.spawn(async move { iter(flag, counter, true) });
656 }
657
658 // Now, hammer the injection queue until the interval drops.
659 let mut n = 0;
660 loop {
661 let curr = interval.load(Relaxed);
662
663 if curr <= 8 {
664 n += 1;
665 } else {
666 n = 0;
667 }
668
669 // Make sure we get a few good rounds. Jitter in the tuning could result
670 // in one "good" value without being representative of reaching a good
671 // state.
672 if n == 3 {
673 break;
674 }
675
676 if Arc::strong_count(&interval) < 5_000 {
677 let counter = counter.clone();
678 let interval = interval.clone();
679
680 rt.spawn(async move {
681 let prev = counter.swap(0, Relaxed);
682 interval.store(prev, Relaxed);
683 });
684
685 std::thread::yield_now();
686 }
687 }
688
689 flag.store(false, Relaxed);
690
691 let w = Arc::downgrade(&interval);
692 drop(interval);
693
694 while w.strong_count() > 0 {
695 std::thread::sleep(Duration::from_micros(500));
696 }
697
698 // Now, run it again with a faster task
699 let flag = Arc::new(AtomicBool::new(true));
700 // Set it high, we know it shouldn't ever really be this high
701 let counter = Arc::new(AtomicUsize::new(10_000));
702 let interval = Arc::new(AtomicUsize::new(10_000));
703
704 {
705 let flag = flag.clone();
706 let counter = counter.clone();
707 rt.spawn(async move { iter(flag, counter, false) });
708 }
709
710 // Now, hammer the injection queue until the interval reaches the expected range.
711 let mut n = 0;
712 loop {
713 let curr = interval.load(Relaxed);
714
715 if curr <= 1_000 && curr > 32 {
716 n += 1;
717 } else {
718 n = 0;
719 }
720
721 if n == 3 {
722 break;
723 }
724
725 if Arc::strong_count(&interval) <= 5_000 {
726 let counter = counter.clone();
727 let interval = interval.clone();
728
729 rt.spawn(async move {
730 let prev = counter.swap(0, Relaxed);
731 interval.store(prev, Relaxed);
732 });
733 }
734
735 std::thread::yield_now();
736 }
737
738 flag.store(false, Relaxed);
739 }
740
741 fn rt() -> runtime::Runtime {
742 runtime::Builder::new_multi_thread_alt()
743 .enable_all()
744 .build()
745 .unwrap()
746 }