Debian Codegraph @

third_party/rust/tokio/tests/task_join_set.rs

raw
1 #![allow(unknown_lints, unexpected_cfgs)]
2 #![warn(rust_2018_idioms)]
3 #![cfg(feature = "full")]
4
5 use futures::future::FutureExt;
6 use tokio::sync::oneshot;
7 use tokio::task::JoinSet;
8 use tokio::time::Duration;
9
10 fn rt() -> tokio::runtime::Runtime {
11 tokio::runtime::Builder::new_current_thread()
12 .build()
13 .unwrap()
14 }
15
16 #[tokio::test(start_paused = true)]
17 async fn test_with_sleep() {
18 let mut set = JoinSet::new();
19
20 for i in 0..10 {
21 set.spawn(async move { i });
22 assert_eq!(set.len(), 1 + i);
23 }
24 set.detach_all();
25 assert_eq!(set.len(), 0);
26
27 assert!(set.join_next().await.is_none());
28
29 for i in 0..10 {
30 set.spawn(async move {
31 tokio::time::sleep(Duration::from_secs(i as u64)).await;
32 i
33 });
34 assert_eq!(set.len(), 1 + i);
35 }
36
37 let mut seen = [false; 10];
38 while let Some(res) = set.join_next().await.transpose().unwrap() {
39 seen[res] = true;
40 }
41
42 for was_seen in &seen {
43 assert!(was_seen);
44 }
45 assert!(set.join_next().await.is_none());
46
47 // Do it again.
48 for i in 0..10 {
49 set.spawn(async move {
50 tokio::time::sleep(Duration::from_secs(i as u64)).await;
51 i
52 });
53 }
54
55 let mut seen = [false; 10];
56 while let Some(res) = set.join_next().await.transpose().unwrap() {
57 seen[res] = true;
58 }
59
60 for was_seen in &seen {
61 assert!(was_seen);
62 }
63 assert!(set.join_next().await.is_none());
64 }
65
66 #[tokio::test]
67 async fn test_abort_on_drop() {
68 let mut set = JoinSet::new();
69
70 let mut recvs = Vec::new();
71
72 for _ in 0..16 {
73 let (send, recv) = oneshot::channel::<()>();
74 recvs.push(recv);
75
76 set.spawn(async {
77 // This task will never complete on its own.
78 futures::future::pending::<()>().await;
79 drop(send);
80 });
81 }
82
83 drop(set);
84
85 for recv in recvs {
86 // The task is aborted soon and we will receive an error.
87 assert!(recv.await.is_err());
88 }
89 }
90
91 #[tokio::test]
92 async fn alternating() {
93 let mut set = JoinSet::new();
94
95 assert_eq!(set.len(), 0);
96 set.spawn(async {});
97 assert_eq!(set.len(), 1);
98 set.spawn(async {});
99 assert_eq!(set.len(), 2);
100
101 for _ in 0..16 {
102 let () = set.join_next().await.unwrap().unwrap();
103 assert_eq!(set.len(), 1);
104 set.spawn(async {});
105 assert_eq!(set.len(), 2);
106 }
107 }
108
109 #[tokio::test(start_paused = true)]
110 async fn abort_tasks() {
111 let mut set = JoinSet::new();
112 let mut num_canceled = 0;
113 let mut num_completed = 0;
114 for i in 0..16 {
115 let abort = set.spawn(async move {
116 tokio::time::sleep(Duration::from_secs(i as u64)).await;
117 i
118 });
119
120 if i % 2 != 0 {
121 // abort odd-numbered tasks.
122 abort.abort();
123 }
124 }
125 loop {
126 match set.join_next().await {
127 Some(Ok(res)) => {
128 num_completed += 1;
129 assert_eq!(res % 2, 0);
130 }
131 Some(Err(e)) => {
132 assert!(e.is_cancelled());
133 num_canceled += 1;
134 }
135 None => break,
136 }
137 }
138
139 assert_eq!(num_canceled, 8);
140 assert_eq!(num_completed, 8);
141 }
142
143 #[test]
144 fn runtime_gone() {
145 let mut set = JoinSet::new();
146 {
147 let rt = rt();
148 set.spawn_on(async { 1 }, rt.handle());
149 drop(rt);
150 }
151
152 assert!(rt()
153 .block_on(set.join_next())
154 .unwrap()
155 .unwrap_err()
156 .is_cancelled());
157 }
158
159 #[tokio::test(start_paused = true)]
160 async fn abort_all() {
161 let mut set: JoinSet<()> = JoinSet::new();
162
163 for _ in 0..5 {
164 set.spawn(futures::future::pending());
165 }
166 for _ in 0..5 {
167 set.spawn(async {
168 tokio::time::sleep(Duration::from_secs(1)).await;
169 });
170 }
171
172 // The join set will now have 5 pending tasks and 5 ready tasks.
173 tokio::time::sleep(Duration::from_secs(2)).await;
174
175 set.abort_all();
176 assert_eq!(set.len(), 10);
177
178 let mut count = 0;
179 while let Some(res) = set.join_next().await {
180 if let Err(err) = res {
181 assert!(err.is_cancelled());
182 }
183 count += 1;
184 }
185 assert_eq!(count, 10);
186 assert_eq!(set.len(), 0);
187 }
188
189 // This ensures that `join_next` works correctly when the coop budget is
190 // exhausted.
191 #[tokio::test(flavor = "current_thread")]
192 async fn join_set_coop() {
193 // Large enough to trigger coop.
194 const TASK_NUM: u32 = 1000;
195
196 static SEM: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(0);
197
198 let mut set = JoinSet::new();
199
200 for _ in 0..TASK_NUM {
201 set.spawn(async {
202 SEM.add_permits(1);
203 });
204 }
205
206 // Wait for all tasks to complete.
207 //
208 // Since this is a `current_thread` runtime, there's no race condition
209 // between the last permit being added and the task completing.
210 let _ = SEM.acquire_many(TASK_NUM).await.unwrap();
211
212 let mut count = 0;
213 let mut coop_count = 0;
214 loop {
215 match set.join_next().now_or_never() {
216 Some(Some(Ok(()))) => {}
217 Some(Some(Err(err))) => panic!("failed: {}", err),
218 None => {
219 coop_count += 1;
220 tokio::task::yield_now().await;
221 continue;
222 }
223 Some(None) => break,
224 }
225
226 count += 1;
227 }
228 assert!(coop_count >= 1);
229 assert_eq!(count, TASK_NUM);
230 }
231
232 #[tokio::test(flavor = "current_thread")]
233 async fn try_join_next() {
234 const TASK_NUM: u32 = 1000;
235
236 let (send, recv) = tokio::sync::watch::channel(());
237
238 let mut set = JoinSet::new();
239
240 for _ in 0..TASK_NUM {
241 let mut recv = recv.clone();
242 set.spawn(async move { recv.changed().await.unwrap() });
243 }
244 drop(recv);
245
246 assert!(set.try_join_next().is_none());
247
248 send.send_replace(());
249 send.closed().await;
250
251 let mut count = 0;
252 loop {
253 match set.try_join_next() {
254 Some(Ok(())) => {
255 count += 1;
256 }
257 Some(Err(err)) => panic!("failed: {}", err),
258 None => {
259 break;
260 }
261 }
262 }
263
264 assert_eq!(count, TASK_NUM);
265 }
266
267 #[cfg(tokio_unstable)]
268 #[tokio::test(flavor = "current_thread")]
269 async fn try_join_next_with_id() {
270 const TASK_NUM: u32 = 1000;
271
272 let (send, recv) = tokio::sync::watch::channel(());
273
274 let mut set = JoinSet::new();
275 let mut spawned = std::collections::HashSet::with_capacity(TASK_NUM as usize);
276
277 for _ in 0..TASK_NUM {
278 let mut recv = recv.clone();
279 let handle = set.spawn(async move { recv.changed().await.unwrap() });
280
281 spawned.insert(handle.id());
282 }
283 drop(recv);
284
285 assert!(set.try_join_next_with_id().is_none());
286
287 send.send_replace(());
288 send.closed().await;
289
290 let mut count = 0;
291 let mut joined = std::collections::HashSet::with_capacity(TASK_NUM as usize);
292 loop {
293 match set.try_join_next_with_id() {
294 Some(Ok((id, ()))) => {
295 count += 1;
296 joined.insert(id);
297 }
298 Some(Err(err)) => panic!("failed: {}", err),
299 None => {
300 break;
301 }
302 }
303 }
304
305 assert_eq!(count, TASK_NUM);
306 assert_eq!(joined, spawned);
307 }