Skip to main content

vortex_io/runtime/
current.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::future::Future;
5use std::pin::pin;
6use std::sync::Arc;
7
8use async_channel::TryRecvError;
9use futures::FutureExt;
10use futures::SinkExt;
11use futures::Stream;
12use futures::StreamExt;
13use futures::channel::mpsc;
14use futures::stream::BoxStream;
15use parking_lot::Mutex;
16use smol::block_on;
17use vortex_utils::parallelism::get_available_parallelism;
18
19use crate::runtime::BlockingRuntime;
20use crate::runtime::Executor;
21use crate::runtime::Handle;
22pub use crate::runtime::pool::CurrentThreadWorkerPool;
23use crate::runtime::smol::SmolExecutor;
24
25/// A current thread runtime allows callers to much more explicitly drive Vortex futures than with
26/// a Tokio runtime.
27///
28/// The current thread runtime will do no work unless `block_on` is called. In other words, the
29/// default behavior is single-threaded with code running on the thread that called `block_on`.
30///
31/// It's also possible to clone the runtime onto other threads, each of which can call `block_on`
32/// to drive work on that thread. Each thread shares the same underlying executor with the same
33/// set of tasks, allowing work to be driven in parallel.
34///
35/// For automatic driving of work, a [`CurrentThreadWorkerPool`] can be created from the runtime
36/// by calling [`new_pool`](CurrentThreadRuntime::new_pool). The returned pool can be configured
37/// with the desired number of worker threads that will drive work on behalf of the runtime.
38#[derive(Clone, Default)]
39pub struct CurrentThreadRuntime {
40    executor: Arc<SmolExecutor>,
41}
42
43impl CurrentThreadRuntime {
44    /// Create a new current thread runtime.
45    pub fn new() -> Self {
46        Self::default()
47    }
48
49    /// Create a new worker pool for driving the runtime in the background.
50    ///
51    /// This pool can be used to offload work from the current thread to a set of worker threads
52    /// that will drive the runtime's executor.
53    ///
54    /// By default, the pool has no worker threads; the caller must set the desired number of
55    /// worker threads using the `set_workers` method on the returned pool.
56    pub fn new_pool(&self) -> CurrentThreadWorkerPool {
57        CurrentThreadWorkerPool::new(Arc::clone(&self.executor))
58    }
59
60    /// Returns an iterator wrapper around a stream, blocking the current thread for each item.
61    ///
62    /// ## Multi-threaded Usage
63    ///
64    /// To drive the iterator from multiple threads, simply clone it and call `next()` on each
65    /// clone. Results on each thread are ordered with respect to the stream, but there is no
66    /// ordering guarantee between threads.
67    pub fn block_on_stream_thread_safe<F, S, R>(&self, f: F) -> ThreadSafeIterator<R>
68    where
69        F: FnOnce(Handle) -> S,
70        S: Stream<Item = R> + Send + 'static,
71        R: Send + 'static,
72    {
73        let stream = f(self.handle());
74
75        // We create an MPMC result channel and spawn a task to drive the stream and send results.
76        // This allows multiple worker threads to drive the execution while all waiting for results
77        // on the channel. Channel buffers up to one item per core so calling threads can get a
78        // ready item without every one of them having to become an executor.
79        let capacity = get_available_parallelism().unwrap_or(1).max(1);
80        let (result_tx, result_rx) = async_channel::bounded(capacity);
81        let driver = self.executor.async_executor().spawn(async move {
82            futures::pin_mut!(stream);
83            while let Some(item) = stream.next().await {
84                // If all receivers are dropped, we stop driving the stream.
85                if let Err(e) = result_tx.send(item).await {
86                    tracing::trace!("all receivers dropped, stopping stream: {}", e);
87                    break;
88                }
89            }
90        });
91
92        ThreadSafeIterator {
93            executor: Arc::clone(&self.executor),
94            results: result_rx,
95            driver: Arc::new(Mutex::new(Some(driver))),
96        }
97    }
98
99    /// Returns an iterator that drives a stream in a background task, keeping at most one
100    /// completed item ready ahead of the single consumer.
101    ///
102    /// Use this instead of [`block_on_stream_thread_safe`](Self::block_on_stream_thread_safe)
103    /// when items are large and a per-core output queue would retain too many of them.
104    pub fn block_on_stream_prefetch<S, R>(&self, stream: S) -> PrefetchIterator<R>
105    where
106        S: Stream<Item = R> + Send + 'static,
107        R: Send + 'static,
108    {
109        // A zero-capacity mpsc still gives the sender one slot, and `send` resolves only once the
110        // receiver takes the item, so the driver never pulls a second item ahead.
111        let (mut result_tx, result_rx) = mpsc::channel(0);
112        let driver = self.executor.async_executor().spawn(async move {
113            futures::pin_mut!(stream);
114            while let Some(item) = stream.next().await {
115                if result_tx.send(item).await.is_err() {
116                    break;
117                }
118            }
119        });
120
121        PrefetchIterator {
122            executor: Arc::clone(&self.executor),
123            results: result_rx,
124            driver: Some(driver),
125        }
126    }
127}
128
129impl BlockingRuntime for CurrentThreadRuntime {
130    type BlockingIterator<'a, R: 'a> = CurrentThreadIterator<'a, R>;
131
132    fn handle(&self) -> Handle {
133        let executor: Arc<dyn Executor> = Arc::clone(&self.executor) as Arc<dyn Executor>;
134        Handle::new(Arc::downgrade(&executor))
135    }
136
137    fn block_on<Fut, R>(&self, fut: Fut) -> R
138    where
139        Fut: Future<Output = R>,
140    {
141        drive(&self.executor, fut)
142    }
143
144    fn block_on_stream<'a, S, R>(&self, stream: S) -> Self::BlockingIterator<'a, R>
145    where
146        S: Stream<Item = R> + Send + 'a,
147        R: Send + 'a,
148    {
149        CurrentThreadIterator {
150            executor: Arc::clone(&self.executor),
151            stream: stream.boxed(),
152        }
153    }
154}
155
156/// Drives `fut` to completion on the calling thread.
157fn drive<Fut: Future>(executor: &SmolExecutor, fut: Fut) -> Fut::Output {
158    let mut fut = pin!(fut);
159    if let Some(output) = fut.as_mut().now_or_never() {
160        return output;
161    }
162    block_on(executor.run(fut))
163}
164
165/// An iterator that wraps up a stream to drive it using the current thread execution.
166pub struct CurrentThreadIterator<'a, T> {
167    executor: Arc<SmolExecutor>,
168    stream: BoxStream<'a, T>,
169}
170
171impl<T> Iterator for CurrentThreadIterator<'_, T> {
172    type Item = T;
173
174    fn next(&mut self) -> Option<Self::Item> {
175        drive(&self.executor, self.stream.next())
176    }
177}
178
179/// An iterator that drives a stream from multiple threads.
180pub struct ThreadSafeIterator<T> {
181    executor: Arc<SmolExecutor>,
182    results: async_channel::Receiver<T>,
183    /// Handle to the task driving the stream. Once the stream ends, the first consumer to
184    /// observe it joins the task so a panic raised while driving the stream is re-raised rather
185    /// than silently ending the iterator.
186    driver: Arc<Mutex<Option<smol::Task<()>>>>,
187}
188
189// Manual clone implementation since `T` does not need to be `Clone`.
190impl<T> Clone for ThreadSafeIterator<T> {
191    fn clone(&self) -> Self {
192        Self {
193            executor: Arc::clone(&self.executor),
194            results: self.results.clone(),
195            driver: Arc::clone(&self.driver),
196        }
197    }
198}
199
200impl<T> Iterator for ThreadSafeIterator<T> {
201    type Item = T;
202
203    fn next(&mut self) -> Option<Self::Item> {
204        // If driver already has an item, take it without driving the executor
205        match self.results.try_recv() {
206            Ok(item) => return Some(item),
207            Err(TryRecvError::Empty) => {}
208            Err(TryRecvError::Closed) => return self.get_task_error(),
209        }
210
211        match block_on(self.executor.run(self.results.recv())) {
212            Ok(item) => Some(item),
213            Err(_) => self.get_task_error(),
214        }
215    }
216}
217
218impl<T> ThreadSafeIterator<T> {
219    // Join current task so panics are re-raised
220    fn get_task_error(&self) -> Option<T> {
221        let task = self.driver.lock().take();
222        if let Some(task) = task {
223            block_on(self.executor.run(task));
224        }
225        None
226    }
227}
228
229/// A single-consumer iterator that keeps at most one completed item ahead of the consumer.
230pub struct PrefetchIterator<T> {
231    executor: Arc<SmolExecutor>,
232    results: mpsc::Receiver<T>,
233    /// Joined once the stream ends so a panic raised while driving it is re-raised.
234    driver: Option<smol::Task<()>>,
235}
236
237impl<T> Iterator for PrefetchIterator<T> {
238    type Item = T;
239
240    fn next(&mut self) -> Option<Self::Item> {
241        let item = match self.results.try_recv() {
242            Ok(item) => Some(item),
243            Err(mpsc::TryRecvError::Closed) => None,
244            Err(mpsc::TryRecvError::Empty) => block_on(self.executor.run(self.results.next())),
245        };
246        if item.is_none()
247            && let Some(driver) = self.driver.take()
248        {
249            block_on(self.executor.run(driver));
250        }
251        item
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use std::any::Any;
258    use std::panic::AssertUnwindSafe;
259    use std::sync::Arc;
260    use std::sync::Barrier;
261    use std::sync::atomic::AtomicUsize;
262    use std::sync::atomic::Ordering;
263    use std::task::Poll;
264    use std::thread;
265    use std::time::Duration;
266
267    use futures::StreamExt;
268    use futures::stream;
269    use parking_lot::Mutex;
270
271    use super::*;
272
273    #[test]
274    fn block_on_runs_tasks_for_a_future_that_is_not_ready() {
275        let runtime = CurrentThreadRuntime::new();
276        assert_eq!(runtime.block_on(async { 7 }), 7);
277        // The spawned task has not run when the future is first polled, so it is ready only once
278        // block_on enters the executor, which runs the task.
279        let task = runtime.handle().spawn(async { 11 });
280        assert_eq!(runtime.block_on(task), 11);
281    }
282
283    #[test]
284    fn test_worker_thread() {
285        let runtime = CurrentThreadRuntime::new();
286
287        // We spawn a future that sets a value on a separate thread.
288        let value = Arc::new(AtomicUsize::new(0));
289        let value2 = Arc::clone(&value);
290        runtime
291            .handle()
292            .spawn(async move {
293                value2.store(42, Ordering::SeqCst);
294            })
295            .detach();
296
297        // By default, nothing has driven the executor, so the value should still be 0.
298        assert_eq!(value.load(Ordering::SeqCst), 0);
299
300        // An empty pool still does nothing.
301        let pool = runtime.new_pool();
302        assert_eq!(value.load(Ordering::SeqCst), 0);
303
304        // Adding a worker thread should drive the executor.
305        pool.set_workers(1);
306        for _ in 0..10 {
307            if value.load(Ordering::SeqCst) == 42 {
308                break;
309            }
310            thread::sleep(Duration::from_millis(10));
311        }
312        assert_eq!(value.load(Ordering::SeqCst), 42);
313    }
314
315    #[test]
316    fn test_block_on_stream_single_thread() {
317        let mut iter =
318            CurrentThreadRuntime::new().block_on_stream(stream::iter(vec![1, 2, 3, 4, 5]).boxed());
319
320        assert_eq!(iter.next(), Some(1));
321        assert_eq!(iter.next(), Some(2));
322        assert_eq!(iter.next(), Some(3));
323        assert_eq!(iter.next(), Some(4));
324        assert_eq!(iter.next(), Some(5));
325        assert_eq!(iter.next(), None);
326    }
327
328    #[test]
329    fn test_block_on_stream_multiple_threads() {
330        let counter = Arc::new(AtomicUsize::new(0));
331        let num_threads = 4;
332        let items_per_thread = 25;
333        let total_items = 100;
334
335        let iter = CurrentThreadRuntime::new()
336            .block_on_stream_thread_safe(|_h| stream::iter(0..total_items).boxed());
337
338        let barrier = Arc::new(Barrier::new(num_threads));
339        let results = Arc::new(Mutex::new(Vec::new()));
340
341        let threads: Vec<_> = (0..num_threads)
342            .map(|_| {
343                let mut iter = iter.clone();
344                let counter = Arc::clone(&counter);
345                let barrier = Arc::clone(&barrier);
346                let results = Arc::clone(&results);
347
348                thread::spawn(move || {
349                    barrier.wait();
350                    let mut local_results = Vec::new();
351
352                    for _ in 0..items_per_thread {
353                        if let Some(item) = iter.next() {
354                            counter.fetch_add(1, Ordering::SeqCst);
355                            local_results.push(item);
356                        }
357                    }
358
359                    results.lock().push(local_results);
360                })
361            })
362            .collect();
363
364        for thread in threads {
365            thread.join().unwrap();
366        }
367
368        assert_eq!(counter.load(Ordering::SeqCst), total_items);
369
370        let all_results = results.lock();
371        let mut collected: Vec<_> = all_results.iter().flatten().copied().collect();
372        collected.sort();
373        assert_eq!(collected, (0..total_items).collect::<Vec<_>>());
374    }
375
376    #[test]
377    fn test_block_on_stream_thread_safe_propagates_driver_panic() {
378        let runtime = CurrentThreadRuntime::new();
379        let mut iter = runtime.block_on_stream_thread_safe(|_h| {
380            stream::poll_fn(|_| -> Poll<Option<usize>> {
381                panic!("stream driver panic");
382            })
383            .boxed()
384        });
385
386        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| iter.next()))
387            .expect_err("stream panic must propagate through iterator");
388        let message = panic
389            .downcast_ref::<&'static str>()
390            .copied()
391            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
392            .unwrap_or("<unknown panic>");
393        assert!(message.contains("stream driver panic"));
394    }
395
396    fn panic_message(panic: &(dyn Any + Send)) -> &str {
397        panic
398            .downcast_ref::<&'static str>()
399            .copied()
400            .or_else(|| panic.downcast_ref::<String>().map(String::as_str))
401            .unwrap_or("<unknown panic>")
402    }
403
404    // A driver panic must propagate on *every* run, regardless of executor scheduling. Running
405    // the scenario many times guards against a return to timing-dependent propagation.
406    #[test]
407    fn test_block_on_stream_thread_safe_panic_propagation_is_deterministic() {
408        for i in 0..2000 {
409            let mut iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|_h| {
410                stream::poll_fn(|_| -> Poll<Option<usize>> {
411                    panic!("deterministic driver panic");
412                })
413                .boxed()
414            });
415
416            let outcome = std::panic::catch_unwind(AssertUnwindSafe(|| iter.next()));
417            assert!(
418                outcome.is_err(),
419                "driver panic was swallowed on iteration {i}: next() returned {:?}",
420                outcome.ok().flatten(),
421            );
422        }
423    }
424
425    // A panic after some items were already produced must still surface, not be seen as a clean
426    // end of stream.
427    #[test]
428    fn test_block_on_stream_thread_safe_panic_after_items() {
429        let mut emitted = 0usize;
430        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(move |_h| {
431            stream::poll_fn(move |_| -> Poll<Option<usize>> {
432                if emitted < 3 {
433                    emitted += 1;
434                    Poll::Ready(Some(emitted))
435                } else {
436                    panic!("driver panic after items");
437                }
438            })
439            .boxed()
440        });
441
442        // Drain the iterator. The terminal event must be a propagated panic, never a clean
443        // `None`. This avoids depending on exactly how many buffered items survive channel close.
444        let outcome = std::panic::catch_unwind(AssertUnwindSafe(move || iter.collect::<Vec<_>>()));
445        match outcome {
446            Ok(items) => panic!("driver panic was swallowed; stream ended cleanly with {items:?}"),
447            Err(panic) => assert!(panic_message(&*panic).contains("driver panic after items")),
448        }
449    }
450
451    // With multiple consumers, a driver panic must reach *every* consumer that observes the end
452    // of the stream; it must never be swallowed by all of them. Exactly one consumer joins the
453    // driver and observes the panic; the rest see the stream end.
454    #[test]
455    fn test_block_on_stream_thread_safe_multi_consumer_panic_surfaced() {
456        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|_h| {
457            stream::poll_fn(|_| -> Poll<Option<usize>> {
458                panic!("multi consumer driver panic");
459            })
460            .boxed()
461        });
462
463        let num_threads = 4;
464        let barrier = Arc::new(Barrier::new(num_threads));
465        let panics = Arc::new(AtomicUsize::new(0));
466
467        let handles: Vec<_> = (0..num_threads)
468            .map(|_| {
469                let mut iter = iter.clone();
470                let barrier = Arc::clone(&barrier);
471                let panics = Arc::clone(&panics);
472                thread::spawn(move || {
473                    barrier.wait();
474                    match std::panic::catch_unwind(AssertUnwindSafe(|| iter.next())) {
475                        // The driver panicked before producing anything, so a clean end is the
476                        // only non-panic outcome a consumer may observe.
477                        Ok(None) => {}
478                        Ok(Some(_)) => panic!("no item was produced before the driver panicked"),
479                        Err(panic) => {
480                            assert!(panic_message(&*panic).contains("multi consumer driver panic"));
481                            panics.fetch_add(1, Ordering::SeqCst);
482                        }
483                    }
484                })
485            })
486            .collect();
487
488        for handle in handles {
489            handle.join().expect("consumer thread panicked uncaught");
490        }
491
492        // The panic surfaces to exactly one consumer and is never swallowed by all of them.
493        assert_eq!(panics.load(Ordering::SeqCst), 1);
494    }
495
496    // Clean completion must return `None` with no spurious panic.
497    #[test]
498    fn test_block_on_stream_thread_safe_clean_completion_returns_none() {
499        let mut iter = CurrentThreadRuntime::new()
500            .block_on_stream_thread_safe(|_h| stream::iter(vec![1usize, 2, 3]).boxed());
501
502        assert_eq!(iter.next(), Some(1));
503        assert_eq!(iter.next(), Some(2));
504        assert_eq!(iter.next(), Some(3));
505        assert_eq!(iter.next(), None);
506        assert_eq!(iter.next(), None);
507    }
508
509    #[test]
510    fn test_block_on_stream_concurrent_clone_and_drive() {
511        let num_items = 50;
512        let num_threads = 3;
513
514        let iter = CurrentThreadRuntime::new().block_on_stream_thread_safe(|h| {
515            stream::unfold(0, move |state| {
516                let h = h.clone();
517                async move {
518                    if state < num_items {
519                        h.spawn_cpu(move || {
520                            thread::sleep(Duration::from_micros(10));
521                            state
522                        })
523                        .await;
524                        Some((state, state + 1))
525                    } else {
526                        None
527                    }
528                }
529            })
530        });
531
532        let collected = Arc::new(Mutex::new(Vec::new()));
533        let barrier = Arc::new(Barrier::new(num_threads));
534
535        let threads: Vec<_> = (0..num_threads)
536            .map(|thread_id| {
537                let iter = iter.clone();
538                let collected = Arc::clone(&collected);
539                let barrier = Arc::clone(&barrier);
540
541                thread::spawn(move || {
542                    barrier.wait();
543                    let mut local_items = Vec::new();
544
545                    for item in iter {
546                        local_items.push((thread_id, item));
547                        if local_items.len() >= 5 {
548                            break;
549                        }
550                    }
551
552                    collected.lock().extend(local_items);
553                })
554            })
555            .collect();
556
557        for thread in threads {
558            thread.join().unwrap();
559        }
560
561        let results = collected.lock();
562        let mut values: Vec<_> = results.iter().map(|(_, v)| *v).collect();
563        values.sort();
564        assert_eq!(values, (0..num_threads * 5).collect::<Vec<_>>());
565    }
566
567    #[test]
568    fn test_block_on_stream_async_work() {
569        let runtime = CurrentThreadRuntime::new();
570        let handle = runtime.handle();
571        let iter = runtime.block_on_stream({
572            stream::unfold((handle, 0), |(h, state)| async move {
573                if state < 10 {
574                    let value = h
575                        .spawn(async move { futures::future::ready(state * 2).await })
576                        .await;
577                    Some((value, (h, state + 1)))
578                } else {
579                    None
580                }
581            })
582        });
583
584        let results: Vec<_> = iter.collect();
585        assert_eq!(results, vec![0, 2, 4, 6, 8, 10, 12, 14, 16, 18]);
586    }
587
588    #[test]
589    fn test_block_on_stream_drop_receivers_early() {
590        let counter = Arc::new(AtomicUsize::new(0));
591        let c = Arc::clone(&counter);
592
593        let mut iter = CurrentThreadRuntime::new().block_on_stream({
594            stream::unfold(0, move |state| {
595                let c = Arc::clone(&c);
596                async move {
597                    (state < 100).then(|| {
598                        c.fetch_add(1, Ordering::SeqCst);
599                        (state, state + 1)
600                    })
601                }
602            })
603            .boxed()
604        });
605
606        assert_eq!(iter.next(), Some(0));
607        assert_eq!(iter.next(), Some(1));
608        assert_eq!(iter.next(), Some(2));
609
610        drop(iter);
611
612        let final_count = counter.load(Ordering::SeqCst);
613        assert!(
614            final_count < 100,
615            "Stream should stop when all receivers are dropped"
616        );
617    }
618
619    #[test]
620    fn test_block_on_stream_interleaved_access() {
621        let barrier = Arc::new(Barrier::new(2));
622        let iter = CurrentThreadRuntime::new()
623            .block_on_stream_thread_safe(|_h| stream::iter(0..20).boxed());
624
625        let iter1 = iter.clone();
626        let iter2 = iter;
627        let barrier1 = Arc::clone(&barrier);
628        let barrier2 = barrier;
629
630        let thread1 = thread::spawn(move || {
631            let mut iter = iter1;
632            let mut results = Vec::new();
633            barrier1.wait();
634
635            for _ in 0..5 {
636                if let Some(val) = iter.next() {
637                    results.push(val);
638                    thread::sleep(Duration::from_micros(50));
639                }
640            }
641            results
642        });
643
644        let thread2 = thread::spawn(move || {
645            let mut iter = iter2;
646            let mut results = Vec::new();
647            barrier2.wait();
648
649            for _ in 0..5 {
650                if let Some(val) = iter.next() {
651                    results.push(val);
652                    thread::sleep(Duration::from_micros(50));
653                }
654            }
655            results
656        });
657
658        let results1 = thread1.join().unwrap();
659        let results2 = thread2.join().unwrap();
660
661        let mut all_results = results1;
662        all_results.extend(results2);
663        all_results.sort();
664
665        assert_eq!(all_results, (0..10).collect::<Vec<_>>());
666
667        for i in 0..10 {
668            assert_eq!(all_results.iter().filter(|&&x| x == i).count(), 1);
669        }
670    }
671
672    #[test]
673    fn test_block_on_stream_stress_test() {
674        let num_threads = 10;
675        let num_items = 1000;
676
677        let iter = CurrentThreadRuntime::new()
678            .block_on_stream_thread_safe(|_h| stream::iter(0..num_items).boxed());
679
680        let received = Arc::new(Mutex::new(Vec::new()));
681        let barrier = Arc::new(Barrier::new(num_threads));
682
683        let threads: Vec<_> = (0..num_threads)
684            .map(|_| {
685                let iter = iter.clone();
686                let received = Arc::clone(&received);
687                let barrier = Arc::clone(&barrier);
688
689                thread::spawn(move || {
690                    barrier.wait();
691                    for val in iter {
692                        received.lock().push(val);
693                    }
694                })
695            })
696            .collect();
697
698        for thread in threads {
699            thread.join().unwrap();
700        }
701
702        let mut results = received.lock().clone();
703        results.sort();
704
705        assert_eq!(results.len(), num_items);
706        assert_eq!(results, (0..num_items).collect::<Vec<_>>());
707    }
708
709    #[test]
710    fn test_block_on_stream_prefetch_keeps_one_item_ahead() {
711        let runtime = CurrentThreadRuntime::new();
712        let produced = Arc::new(AtomicUsize::new(0));
713        let counter = Arc::clone(&produced);
714        let items = stream::iter(0..16).inspect(move |_| {
715            counter.fetch_add(1, Ordering::SeqCst);
716        });
717        let mut iter = runtime.block_on_stream_prefetch(items);
718        assert_eq!(iter.next(), Some(0));
719        runtime.block_on(async {
720            for _ in 0..64 {
721                runtime.handle().spawn(async {}).await;
722            }
723        });
724        assert_eq!(produced.load(Ordering::SeqCst), 2);
725        assert_eq!(iter.collect::<Vec<_>>(), (1..16).collect::<Vec<_>>());
726    }
727
728    #[test]
729    fn test_block_on_stream_prefetch_propagates_driver_panic() {
730        let runtime = CurrentThreadRuntime::new();
731        let items = stream::iter(0..2).map(|value| {
732            assert!(value != 1, "stream driver panic");
733            value
734        });
735        let mut iter = runtime.block_on_stream_prefetch(items);
736        assert_eq!(iter.next(), Some(0));
737        let panic = std::panic::catch_unwind(AssertUnwindSafe(|| iter.next()))
738            .expect_err("stream panic must propagate through iterator");
739        assert!(panic_message(panic.as_ref()).contains("stream driver panic"));
740    }
741}