moirai-core 0.7.0

Core abstractions and traits for the Moirai concurrency library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
#![cfg_attr(test, allow(clippy::unwrap_used, reason = "test scope"))]

use super::*;

#[test]
fn test_hybrid_channel() {
    let (tx, rx) = HybridChannel::<i32>::new(4);

    tx.send(42).unwrap();
    assert_eq!(rx.recv().unwrap(), 42);

    assert!(matches!(rx.try_recv(), Err(ChannelError::Empty)));

    let result = rx.recv_timeout(std::time::Duration::from_millis(100));
    assert!(matches!(result, Err(ChannelError::Empty)));

    for i in 0..4 {
        tx.send(i).unwrap();
    }

    assert!(!tx.can_send());
    assert_eq!(tx.available_capacity(), 0);

    let values = rx.drain();
    assert_eq!(values, vec![0, 1, 2, 3]);
}

#[test]
fn test_hybrid_channel_async() {
    use std::future::Future;
    use std::pin::Pin;
    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

    fn dummy_raw_waker() -> RawWaker {
        fn clone_raw(_: *const ()) -> RawWaker {
            dummy_raw_waker()
        }
        fn wake_raw(_: *const ()) {}
        fn wake_by_ref_raw(_: *const ()) {}
        fn drop_raw(_: *const ()) {}
        static VTABLE: RawWakerVTable =
            RawWakerVTable::new(clone_raw, wake_raw, wake_by_ref_raw, drop_raw);
        RawWaker::new(std::ptr::null(), &VTABLE)
    }

    let (tx, rx) = HybridChannel::<i32>::new(4);
    let mut recv_fut = rx.recv_async();

    let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
    let mut cx = Context::from_waker(&waker);

    assert!(matches!(
        Pin::new(&mut recv_fut).poll(&mut cx),
        Poll::Pending
    ));

    tx.send(100).unwrap();

    assert!(matches!(
        Pin::new(&mut recv_fut).poll(&mut cx),
        Poll::Ready(Ok(100))
    ));
}

#[test]
fn test_spsc_channel() {
    let (tx, rx) = spsc::<i32>(4);

    assert!(tx.send(1).is_ok());
    assert!(tx.send(2).is_ok());

    assert_eq!(rx.recv().unwrap(), 1);
    assert_eq!(rx.recv().unwrap(), 2);

    assert!(rx.try_recv().is_err());
}

#[test]
fn test_spsc_thread_safety_bounds() {
    fn assert_send<T: Send>() {}
    assert_send::<SpscSender<i32>>();
    assert_send::<SpscReceiver<i32>>();
}

#[test]
fn test_mpmc_channel() {
    let (tx, rx) = mpmc::<i32>(4);
    let tx2 = tx.clone();

    assert!(tx.send(1).is_ok());
    assert!(tx2.send(2).is_ok());

    let mut values = vec![rx.recv().unwrap(), rx.recv().unwrap()];
    values.sort_unstable();
    assert_eq!(values, vec![1, 2]);
}

#[test]
fn test_mpmc_multi_producer_single_consumer() {
    use std::thread;

    let producer_count = 4;
    let items_per_producer = 1_000;
    let (tx, rx) = mpmc::<usize>(64);

    let consumer = thread::spawn(move || {
        let mut sum = 0usize;
        for _ in 0..(producer_count * items_per_producer) {
            sum += rx.recv().unwrap();
        }
        sum
    });

    let producers = (0..producer_count)
        .map(|producer| {
            let tx = tx.clone();
            thread::spawn(move || {
                for item in 0..items_per_producer {
                    tx.send(producer * items_per_producer + item).unwrap();
                }
            })
        })
        .collect::<Vec<_>>();

    for producer in producers {
        producer.join().unwrap();
    }
    drop(tx);

    let expected = (0..(producer_count * items_per_producer)).sum::<usize>();
    assert_eq!(consumer.join().unwrap(), expected);
}

#[test]
fn test_mpmc_capacity_one_single_producer_consumer() {
    use std::thread;

    // Miri interprets roughly a thousand times slower than native code; the
    // reduced count still drives the full/empty park and wake cycle.
    let item_count = if cfg!(miri) { 128 } else { 32_768 };
    let (tx, rx) = mpmc::<usize>(1);

    let consumer = thread::spawn(move || {
        let mut sum = 0usize;
        for _ in 0..item_count {
            sum += rx.recv().unwrap();
        }
        sum
    });

    let producer = thread::spawn(move || {
        for item in 0..item_count {
            tx.send(item).unwrap();
        }
    });

    producer.join().unwrap();

    let expected = (0..item_count).sum::<usize>();
    assert_eq!(consumer.join().unwrap(), expected);
}

#[test]
fn test_mpmc_capacity_one_repeated_single_producer_consumer() {
    let (rounds, item_count) = if cfg!(miri) { (2, 128) } else { (8, 4_096) };
    for _ in 0..rounds {
        let (tx, rx) = mpmc::<usize>(1);

        let consumer = std::thread::spawn(move || {
            let mut sum = 0usize;
            for _ in 0..item_count {
                sum += rx.recv().unwrap();
            }
            sum
        });

        let producer = std::thread::spawn(move || {
            for item in 0..item_count {
                tx.send(item).unwrap();
            }
        });

        producer.join().unwrap();

        let expected = (0..item_count).sum::<usize>();
        assert_eq!(consumer.join().unwrap(), expected);
    }
}

#[test]
fn test_mpmc_capacity_one_multi_producer_single_consumer() {
    let producer_count = 8;
    let item_count = if cfg!(miri) { 256 } else { 8_192 };
    let (tx, rx) = mpmc::<usize>(1);

    let consumer = std::thread::spawn(move || {
        let mut sum = 0usize;
        for _ in 0..item_count {
            sum += rx.recv().unwrap();
        }
        sum
    });

    let producers = (0..producer_count)
        .map(|producer| {
            let tx = tx.clone();
            std::thread::spawn(move || {
                let base = item_count / producer_count;
                let remainder = item_count % producer_count;
                let start = producer * base + producer.min(remainder);
                let len = base + usize::from(producer < remainder);
                for item in start..(start + len) {
                    tx.send(item).unwrap();
                }
            })
        })
        .collect::<Vec<_>>();

    for producer in producers {
        producer.join().unwrap();
    }
    drop(tx);

    let expected = (0..item_count).sum::<usize>();
    assert_eq!(consumer.join().unwrap(), expected);
}

#[test]
fn test_unbounded_channel() {
    let (tx, rx) = unbounded::<i32>();

    for i in 0..10 {
        tx.send(i).unwrap();
    }

    for i in 0..10 {
        assert_eq!(rx.recv().unwrap(), i);
    }
}

/// A send into a full ring completes only once a receive frees a slot.
///
/// The old form slept 50 ms in the receiver and asserted the send took at
/// least 40 ms, which measures the scheduler rather than the channel and
/// fails on a loaded host. The bound itself is asserted directly --
/// `try_send` must reject while full -- and the blocking send is then
/// synchronized by the receive it is waiting on, so the drained order is
/// what proves it landed after the consume.
#[test]
fn spsc_send_into_a_full_ring_lands_after_the_consume() {
    // Fill by rejection rather than by a count: `spsc(n)` sizes its ring to at
    // least `n`, so the number of accepted sends is the ring's business.
    let (tx, rx) = spsc::<i32>(2);
    let mut filled = 0;
    while tx.try_send(filled).is_ok() {
        filled += 1;
        assert!(
            filled < 1024,
            "a bounded ring must reject before 1024 sends"
        );
    }
    assert!(filled > 0, "a fresh ring accepts at least one value");

    let blocked_value = filled;
    let sender = std::thread::spawn(move || {
        tx.send(blocked_value)
            .expect("the send completes once a slot frees");
        tx
    });

    assert_eq!(
        rx.recv(),
        Ok(0),
        "the receive frees the slot the send needs"
    );
    let tx = sender.join().expect("the sender thread completes");

    for expected in 1..=blocked_value {
        assert_eq!(
            rx.recv(),
            Ok(expected),
            "the blocked value follows the ones already queued"
        );
    }
    std::mem::drop(tx);
}

#[test]
fn test_spsc_drains_value_published_before_close() {
    let (tx, rx) = spsc::<i32>(10);

    let producer = std::thread::spawn(move || {
        tx.send(42).unwrap();
    });
    producer.join().unwrap();

    assert_eq!(rx.recv(), Ok(42));
    assert_eq!(rx.recv(), Err(ChannelError::Closed));
}

/// A receive on an empty hybrid channel parks until a value arrives.
///
/// The old form slept 50 ms before sending and asserted the receive took at
/// least 10 ms, which is a scheduler measurement. Parking is instead shown
/// by what the parked receive observes: it returns the value the sender
/// published after it had already parked, and a second parked receive
/// observes closure when the sender is dropped -- neither outcome is
/// reachable by a receive that returned early.
#[test]
fn hybrid_receive_parks_until_a_value_or_a_close() {
    let (sender, receiver) = HybridChannel::<i32>::new(10);

    let parked = std::thread::spawn(move || {
        let first = receiver.recv();
        let after_close = receiver.recv();
        (first, after_close)
    });

    sender.send(42).expect("the channel has capacity");
    std::mem::drop(sender);

    let (first, after_close) = parked.join().expect("the receiver thread completes");
    assert_eq!(
        first,
        Ok(42),
        "the parked receive takes the published value"
    );
    assert_eq!(
        after_close,
        Err(ChannelError::Closed),
        "a receive parked on an empty channel must observe the sender's drop"
    );
}

#[test]
fn test_spsc_drop_sender() {
    let (tx, rx) = spsc::<i32>(2);
    std::mem::drop(tx);
    assert_eq!(rx.recv(), Err(ChannelError::Closed));
    assert_eq!(rx.try_recv(), Err(ChannelError::Closed));
}

/// A send blocked on a full ring observes the receiver's drop.
///
/// The old form slept 50 ms in the dropping thread so the send would be
/// parked by the time the drop landed -- a race dressed as a delay. Closing
/// from the main thread and reading the parked send's result through its
/// join is the same claim without one: the send can only return `Closed`
/// from inside the park.
#[test]
fn spsc_send_parked_on_a_full_ring_observes_the_receiver_drop() {
    // Fill by rejection rather than by a count: `spsc(n)` sizes its ring to
    // at least `n`, so the number of accepted sends is the ring's business.
    let (tx, rx) = spsc::<i32>(1);
    let mut filled = 0;
    while tx.try_send(filled).is_ok() {
        filled += 1;
        assert!(
            filled < 1024,
            "a bounded ring must reject before 1024 sends"
        );
    }
    assert!(filled > 0, "a fresh ring accepts at least one value");

    let blocked = std::thread::spawn(move || tx.send(2));
    std::mem::drop(rx);

    assert_eq!(
        blocked.join().expect("the sender thread completes"),
        Err(ChannelError::Closed),
        "the parked send must observe the receiver's drop"
    );
}

#[test]
fn test_hybrid_drop_sender() {
    let (tx, rx) = HybridChannel::<i32>::new(2);
    let (ready_tx, ready_rx) = std::sync::mpsc::sync_channel(0);
    let rx_thread = std::thread::spawn(move || {
        // Publish the empty-state observation before entering the blocking
        // receive. The close below is the event that must release it.
        assert!(matches!(rx.try_recv(), Err(ChannelError::Empty)));
        ready_tx.send(()).expect("receiver publishes readiness");
        rx.recv()
    });

    ready_rx
        .recv_timeout(std::time::Duration::from_secs(1))
        .expect("receiver observes the empty channel");
    std::mem::drop(tx);

    assert_eq!(rx_thread.join().unwrap(), Err(ChannelError::Closed));
}

#[test]
fn test_hybrid_drop_receiver() {
    let (tx, rx) = HybridChannel::<i32>::new(2);
    std::mem::drop(rx);
    assert_eq!(tx.send(1), Err(ChannelError::Closed));
    assert_eq!(tx.try_send(1), Err(ChannelError::Closed));
}

/// A bounded channel refuses to grow past its capacity, and a blocking send on
/// a full channel parks instead of allocating.
///
/// The blocking half is proved without a sleep: a parked sender can only leave
/// `send` when a slot frees or the channel closes. Dropping the last receiver
/// closes it, so the send resolves to `Closed` — an implementation that grew
/// the queue instead of blocking would have returned `Ok` with the item
/// accepted.
#[test]
fn bounded_channel_refuses_to_grow_and_blocks_the_producer() {
    use std::thread;

    const CAPACITY: usize = 4;

    let (tx, rx) = mpmc::<usize>(CAPACITY);

    for item in 0..CAPACITY {
        tx.try_send(item)
            .expect("a fresh channel accepts up to its capacity");
    }

    assert_eq!(Producer::capacity(&tx), Some(CAPACITY));
    assert!(Producer::is_full(&tx));
    assert!(
        matches!(tx.try_send(CAPACITY), Err(ChannelError::Full)),
        "a full bounded channel must reject rather than allocate another slot"
    );
    assert_eq!(
        Producer::capacity(&tx),
        Some(CAPACITY),
        "a rejected send must not have moved the bound"
    );

    let blocked = thread::spawn(move || tx.send(CAPACITY));
    drop(rx);

    assert!(
        matches!(blocked.join().unwrap(), Err(ChannelError::Closed)),
        "the send must still have been parked when the channel closed"
    );
}

/// The default capacity is a real bound, not a sentinel for "unbounded".
#[test]
fn default_channel_capacity_bounds_the_queue() {
    let (tx, _rx) = mpmc::<u8>(DEFAULT_CHANNEL_CAPACITY);

    assert_eq!(Producer::capacity(&tx), Some(DEFAULT_CHANNEL_CAPACITY));

    for _ in 0..DEFAULT_CHANNEL_CAPACITY {
        tx.try_send(0).expect("capacity slots are accepted");
    }

    assert!(matches!(tx.try_send(0), Err(ChannelError::Full)));
}