|
| 1 | +// Warning: the test uses the `futures` library. |
| 2 | +// This is available only to the testing code (it is a dev-dependency), |
| 3 | +// it is not available to the solution code. |
| 4 | + |
| 5 | +use std::future::Future; |
| 6 | +use std::pin::Pin; |
| 7 | +use std::sync::Arc; |
| 8 | + |
| 9 | +use futures::{SinkExt, StreamExt}; |
| 10 | +use solution::*; |
| 11 | + |
| 12 | +#[test] |
| 13 | +fn test_futures_join() { |
| 14 | + run_with_timeout(1000, || async { |
| 15 | + let resource = Arc::new(MyMutex::new(vec![])); |
| 16 | + let (mut sender_3to1, mut recv_3to1) = futures::channel::mpsc::channel(1); |
| 17 | + |
| 18 | + let fut1 = { |
| 19 | + // A future that locks the resource, then holds the lock across an |
| 20 | + // await point (awaiting the next message from the channel). |
| 21 | + // |
| 22 | + // With an async-aware mutex this is not a problem - while `fut1` is blocked, |
| 23 | + // `fut2` and `fut3` can still run. So eventually `fut3` will send the message |
| 24 | + // and unblock `fut1`. |
| 25 | + let resource = Arc::clone(&resource); |
| 26 | + async move { |
| 27 | + let mut lock = resource.lock().await; |
| 28 | + let () = recv_3to1.next().await.unwrap(); |
| 29 | + lock.push("one".to_string()); |
| 30 | + } |
| 31 | + }; |
| 32 | + |
| 33 | + let fut2 = { |
| 34 | + let resource = Arc::clone(&resource); |
| 35 | + async move { |
| 36 | + let mut lock = resource.lock().await; |
| 37 | + lock.push("two".to_string()); |
| 38 | + } |
| 39 | + }; |
| 40 | + |
| 41 | + let fut3 = { |
| 42 | + let resource = Arc::clone(&resource); |
| 43 | + async move { |
| 44 | + sender_3to1.send(()).await.unwrap(); |
| 45 | + let mut lock = resource.lock().await; |
| 46 | + lock.push("three".to_string()); |
| 47 | + } |
| 48 | + }; |
| 49 | + |
| 50 | + // `join` polls the futures in order. |
| 51 | + // |
| 52 | + // Also `join` provides a single `Waker`, which just wakes the `Join3` future, |
| 53 | + // which every time polls each of the inner futures in order. |
| 54 | + // So using any waker will "wake" all three futures. |
| 55 | + futures::future::join3(fut1, fut2, fut3).await; |
| 56 | + |
| 57 | + assert_eq!(&*resource.lock().await, &["one", "two", "three"]); |
| 58 | + }); |
| 59 | +} |
| 60 | + |
| 61 | +#[test] |
| 62 | +fn test_futures_unordered() { |
| 63 | + run_with_timeout(1000, || async { |
| 64 | + let resource = Arc::new(MyMutex::new(vec![])); |
| 65 | + let (mut sender_3to1, mut recv_3to1) = futures::channel::mpsc::channel(1); |
| 66 | + |
| 67 | + let fut1 = pin_box({ |
| 68 | + let resource = Arc::clone(&resource); |
| 69 | + async move { |
| 70 | + let mut lock = resource.lock().await; |
| 71 | + let () = recv_3to1.next().await.unwrap(); |
| 72 | + lock.push("one".to_string()); |
| 73 | + } |
| 74 | + }); |
| 75 | + |
| 76 | + let fut2 = pin_box({ |
| 77 | + let resource = Arc::clone(&resource); |
| 78 | + async move { |
| 79 | + let mut lock = resource.lock().await; |
| 80 | + lock.push("two".to_string()); |
| 81 | + } |
| 82 | + }); |
| 83 | + |
| 84 | + let fut3 = pin_box({ |
| 85 | + let resource = Arc::clone(&resource); |
| 86 | + async move { |
| 87 | + sender_3to1.send(()).await.unwrap(); |
| 88 | + let mut lock = resource.lock().await; |
| 89 | + lock.push("three".to_string()); |
| 90 | + } |
| 91 | + }); |
| 92 | + |
| 93 | + // Same example, but uses `FuturesUnordered` instead of `join`. |
| 94 | + // |
| 95 | + // `FuturesUnordered` doesn't guarantee any ordering. |
| 96 | + // Also it is more optimized for a large number of futures and will provide a separate |
| 97 | + // `Waker` for each of the inner futures. |
| 98 | + // So we can test that the correct wakers are being used. |
| 99 | + let mut unordered = futures::stream::FuturesUnordered::from_iter([fut1, fut2, fut3]); |
| 100 | + while let Some(_) = unordered.next().await {} |
| 101 | + |
| 102 | + let mut final_resource = resource.lock().await.clone(); |
| 103 | + final_resource.sort(); |
| 104 | + assert_eq!(final_resource, &["one", "three", "two"]); |
| 105 | + }); |
| 106 | +} |
| 107 | + |
| 108 | +fn run_with_timeout<F, R>(timeout_millis: u64, test_fn: F) |
| 109 | +where |
| 110 | + F: FnOnce() -> R + Send + std::panic::UnwindSafe + 'static, |
| 111 | + R: Future<Output = ()> + 'static, |
| 112 | +{ |
| 113 | + use futures::task::LocalSpawn; |
| 114 | + use std::panic::catch_unwind; |
| 115 | + use std::sync::mpsc; |
| 116 | + |
| 117 | + let (sender, receiver) = mpsc::sync_channel(1); |
| 118 | + |
| 119 | + std::thread::spawn(move || { |
| 120 | + let result = catch_unwind(move || { |
| 121 | + let mut runtime = futures::executor::LocalPool::new(); |
| 122 | + |
| 123 | + let test_future = Box::new(test_fn()); |
| 124 | + runtime.spawner().spawn_local_obj(test_future.into()).unwrap(); |
| 125 | + |
| 126 | + runtime.run(); |
| 127 | + }); |
| 128 | + |
| 129 | + let _ = sender.send(result); |
| 130 | + }); |
| 131 | + |
| 132 | + let timeout = std::time::Duration::from_millis(timeout_millis); |
| 133 | + match receiver.recv_timeout(timeout) { |
| 134 | + Ok(Ok(())) => {} |
| 135 | + Ok(Err(any)) => panic!("test panicked: {}", any.downcast::<&str>().unwrap()), |
| 136 | + Err(mpsc::RecvTimeoutError::Timeout) => panic!("test timed out"), |
| 137 | + Err(mpsc::RecvTimeoutError::Disconnected) => unreachable!(), |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +fn pin_box<F>(fut: F) -> Pin<Box<dyn Future<Output = ()>>> |
| 142 | +where |
| 143 | + F: Future<Output = ()> + 'static, |
| 144 | +{ |
| 145 | + Box::into_pin(Box::new(fut) as Box<dyn Future<Output = ()>>) |
| 146 | +} |
0 commit comments