tachyonix 0.3.1

A very fast asynchronous, multi-producer, single-consumer bounded channel.
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
//! Note: timer-based tests are disabled for MIRI.

#[cfg(not(miri))]
use std::future::Future;
#[cfg(not(miri))]
use std::task::{Context, Poll};
use std::thread;
#[cfg(not(miri))]
use std::time::Duration;

use futures_executor::block_on;
#[cfg(not(miri))]
use futures_task::noop_waker;
#[cfg(not(miri))]
use futures_util::pin_mut;
use tachyonix::{channel, RecvError, SendError, TryRecvError, TrySendError};
#[cfg(not(miri))]
use tachyonix::{RecvTimeoutError, SendTimeoutError};

// Sleep for the provided number of milliseconds.
#[cfg(not(miri))]
fn sleep(millis: u64) {
    thread::sleep(Duration::from_millis(millis));
}
#[cfg(not(miri))]
async fn async_sleep(millis: u64) -> () {
    futures_time::task::sleep(futures_time::time::Duration::from_millis(millis)).await;
}

// Poll the future once and keep it alive for the specified number of
// milliseconds.
#[cfg(not(miri))]
fn poll_once_and_keep_alive<F: Future>(f: F, millis: u64) -> Poll<F::Output> {
    pin_mut!(f);
    let waker = noop_waker();
    let mut cx = Context::from_waker(&waker);

    let res = f.poll(&mut cx);

    // Delay the drop of the original (shadowed) future.
    sleep(millis);

    res
}

// Basic synchronous sending/receiving functionality.
#[cfg(not(miri))]
#[test]
fn try_send_recv() {
    let (s, mut r) = channel(2);

    let th_send = thread::spawn(move || {
        sleep(100);
        assert_eq!(s.try_send(3), Ok(())); // t = t0 + 100
        assert_eq!(s.try_send(7), Ok(())); // t = t0 + 100
        assert_eq!(s.try_send(13), Err(TrySendError::Full(13))); // t = t0 + 100
        sleep(200);
        assert_eq!(s.try_send(42), Ok(())); // t = t0 + 300
    });

    sleep(200);
    assert_eq!(r.try_recv(), Ok(3)); // t = t0 + 200
    assert_eq!(r.try_recv(), Ok(7)); // t = t0 + 200
    assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); // t = t0 + 200
    sleep(200);
    assert_eq!(r.try_recv(), Ok(42)); // t = t0 + 400
    assert_eq!(r.try_recv(), Err(TryRecvError::Closed)); // t = t0 + 400

    th_send.join().unwrap();
}

// Basic asynchronous sending functionality.
#[cfg(not(miri))]
#[test]
fn async_send() {
    let (s, mut r) = channel(2);

    let th_send = thread::spawn(move || {
        block_on(s.send(3)).unwrap();
        block_on(s.send(7)).unwrap();
        block_on(s.send(13)).unwrap(); // blocked until t0 + 300
        sleep(200);
        block_on(s.send(42)).unwrap(); // t = t0 + 500
    });

    sleep(300);
    assert_eq!(r.try_recv(), Ok(3)); // t = t0 + 300
    assert_eq!(r.try_recv(), Ok(7)); // t = t0 + 300
    sleep(100);
    assert_eq!(r.try_recv(), Ok(13)); // t = t0 + 400
    sleep(200);
    assert_eq!(r.try_recv(), Ok(42)); // t = t0 + 600

    th_send.join().unwrap();
}

// Asynchronous sending with timeout.
#[cfg(not(miri))]
#[test]
fn async_send_timeout() {
    let (s, mut r) = channel(2);

    let th_send = thread::spawn(move || {
        block_on(async {
            s.send(1).await.unwrap(); // t = t0
            s.send(2).await.unwrap(); // t = t0
            s.send_timeout(3, async_sleep(200)).await.unwrap(); // blocked from t = t0 to t0 + 100
            assert_eq!(
                s.send_timeout(4, async_sleep(100)).await, // blocked from t = t0 + 100 to y0 + 200
                Err(SendTimeoutError::Timeout(4))
            );
            sleep(200);
            assert_eq!(
                s.send_timeout(5, async_sleep(200)).await, // t = t0 + 400
                Err(SendTimeoutError::Closed(5))
            );
        })
    });

    sleep(100);
    assert_eq!(r.try_recv(), Ok(1)); // t = t0 + 100
    sleep(200);
    assert_eq!(r.try_recv(), Ok(2)); // t = t0 + 300
    assert_eq!(r.try_recv(), Ok(3)); // t = t0 + 300
    assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); // t = t0 + 300
    drop(r);

    th_send.join().unwrap();
}

// Basic asynchronous receiving functionality.
#[cfg(not(miri))]
#[test]
fn async_recv() {
    let (s, mut r) = channel(100);

    let th_send = thread::spawn(move || {
        sleep(100);
        assert_eq!(s.try_send(3), Ok(())); // t = t0 + 100
        assert_eq!(s.try_send(7), Ok(())); // t = t0 + 100
        assert_eq!(s.try_send(42), Ok(())); // t = t0 + 100
        sleep(100);
    });

    assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); // t = t0
    assert_eq!(block_on(r.recv()), Ok(3)); // blocked from t0 to t0 + 100
    assert_eq!(block_on(r.recv()), Ok(7)); // t = t0 + 100
    assert_eq!(block_on(r.recv()), Ok(42)); // t = t0 + 100
    assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); // t = t0 + 100

    th_send.join().unwrap();
}

// Asynchronous receiving with timeout.
#[cfg(not(miri))]
#[test]
fn async_recv_timeout() {
    let (s, mut r) = channel(100);

    let th_send = thread::spawn(move || {
        s.try_send(1).unwrap(); // t = t0
        sleep(200);
        s.try_send(2).unwrap(); // t = t0 + 200
        sleep(300);
        s.try_send(3).unwrap(); // t = t0 + 500
    });

    block_on(async {
        sleep(100);
        assert_eq!(r.recv_timeout(async_sleep(200)).await, Ok(1)); // t = t0 + 100
        assert_eq!(r.recv_timeout(async_sleep(200)).await, Ok(2)); // blocked from t = t0 + 100 to t0 + 200
        assert_eq!(
            r.recv_timeout(async_sleep(200)).await,
            Err(RecvTimeoutError::Timeout)
        ); // blocked from t = t0 + 200 to t0 + 400
        sleep(200);
        assert_eq!(r.recv_timeout(async_sleep(200)).await, Ok(3)); // t = t0 + 600
        assert_eq!(
            r.recv_timeout(async_sleep(200)).await,
            Err(RecvTimeoutError::Closed)
        ); // t = t0 + 600
    });

    th_send.join().unwrap();
}

// Channel closed due to the receiver being dropped.
#[test]
fn send_after_close() {
    let (s, r) = channel(100);

    block_on(s.send(3)).unwrap();
    block_on(s.send(7)).unwrap();

    drop(r);

    assert_eq!(block_on(s.send(13)), Err(SendError(13)));
    assert_eq!(s.try_send(42), Err(TrySendError::Closed(42)));
}

// Channel closed due to the receiver being dropped while a sender is blocked on
// a full channel.
#[cfg(not(miri))]
#[test]
fn blocked_send_after_close() {
    let (s1, r) = channel(2);
    let s2 = s1.clone();

    block_on(s1.send(3)).unwrap();
    block_on(s1.send(7)).unwrap();

    let th_send1 = thread::spawn(move || {
        assert_eq!(block_on(s1.send(13)), Err(SendError(13))); // blocked from t0 to t0 + 100
    });
    let th_send2 = thread::spawn(move || {
        assert_eq!(block_on(s2.send(42)), Err(SendError(42))); // blocked from t0 to t0 + 100
    });

    sleep(100);
    drop(r); // t = t0 + 100

    th_send1.join().unwrap();
    th_send2.join().unwrap();
}

// Channel closed due to the senders being dropped.
#[test]
fn recv_after_close() {
    let (s1, mut r) = channel(100);
    let s2 = s1.clone();

    block_on(s1.send(3)).unwrap();
    block_on(s1.send(7)).unwrap();
    block_on(s2.send(13)).unwrap();

    drop(s1);
    drop(s2);

    assert_eq!(block_on(r.recv()), Ok(3));
    assert_eq!(block_on(r.recv()), Ok(7));
    assert_eq!(block_on(r.recv()), Ok(13));
    assert_eq!(block_on(r.recv()), Err(RecvError));
    assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
}

// Channel closed due to the senders being dropped while the receiver is blocked
// on an empty channel.
#[cfg(not(miri))]
#[test]
fn blocked_recv_after_close() {
    let (s1, mut r) = channel(100);
    let s2 = s1.clone();

    block_on(s1.send(3)).unwrap();
    block_on(s1.send(7)).unwrap();
    block_on(s2.send(13)).unwrap();

    let th_recv = thread::spawn(move || {
        assert_eq!(block_on(r.recv()), Ok(3));
        assert_eq!(block_on(r.recv()), Ok(7));
        assert_eq!(block_on(r.recv()), Ok(13));
        assert_eq!(block_on(r.recv()), Err(RecvError)); // blocked from t0 to t0 + 100
        assert_eq!(r.try_recv(), Err(TryRecvError::Closed));
    });

    sleep(100);
    drop(s1);
    drop(s2);

    th_recv.join().unwrap();
}

// Block two senders on a full channel, cancel the first sending operation and
// receive a message to unblock the second sender.
#[cfg(not(miri))]
#[test]
fn cancel_async_send() {
    let (s1, mut r) = channel(2);
    let s2 = s1.clone();

    // Fill the channel and block a sender, then cancel the sending operation at
    // t0 + 300.
    let th_send1 = thread::spawn(move || {
        block_on(s1.send(3)).unwrap();
        block_on(s1.send(7)).unwrap();
        assert_eq!(poll_once_and_keep_alive(s1.send(13), 300), Poll::Pending); // cancel at t0 + 300
    });

    // Block a second sender from t0 + 100, expect it to get re-scheduled when the
    // sending operation of the first blocked sender is cancelled.
    let th_send2 = thread::spawn(move || {
        sleep(100);
        block_on(s2.send(42)).unwrap(); // blocked from t0 + 100 to t0 + 300
    });

    // Receive a message at t0 + 200 to free one channel slot; receive the
    // remaining messages at t0 + 400.
    let th_recv = thread::spawn(move || {
        sleep(200);
        assert_eq!(block_on(r.recv()), Ok(3)); // t = t0 + 200
        sleep(200);
        assert_eq!(r.try_recv(), Ok(7)); // t = t0 + 400
        assert_eq!(r.try_recv(), Ok(42)); // t = t0 + 400
    });

    th_send1.join().unwrap();
    th_send2.join().unwrap();
    th_recv.join().unwrap();
}

// Block two senders on a full channel, stop polling the first sender and
// receive two messages to unblock the second sender.
#[cfg(not(miri))]
#[test]
fn forget_async_send() {
    let (s1, mut r) = channel(2);
    let s2 = s1.clone();

    // Fill the channel and block a sender, then stop polling it for a long
    // time.
    let th_send1 = thread::spawn(move || {
        block_on(s1.send(3)).unwrap();
        block_on(s1.send(7)).unwrap();
        assert_eq!(poll_once_and_keep_alive(s1.send(13), 500), Poll::Pending);
    });

    // Block a second sender from t0 + 100, expect it to get re-scheduled when the
    // second message is received.
    let th_send2 = thread::spawn(move || {
        sleep(100);
        block_on(s2.send(42)).unwrap(); // blocked from t0 + 100 to t0 + 200
    });

    // Receive two message at t0 + 200 to free both channel slots; receive one
    // more message at t0 + 300 to check that the second sender got
    // re-scheduled.
    let th_recv = thread::spawn(move || {
        sleep(200);
        assert_eq!(block_on(r.recv()), Ok(3)); // t = t0 + 200
        assert_eq!(block_on(r.recv()), Ok(7)); // t = t0 + 200
        sleep(100);
        assert_eq!(r.try_recv(), Ok(42)); // t = t0 + 300
    });

    th_send1.join().unwrap();
    th_send2.join().unwrap();
    th_recv.join().unwrap();
}

// SPSC stress test.
#[test]
fn spsc_stress() {
    const CAPACITY: usize = 3;
    const COUNT: usize = if cfg!(miri) { 50 } else { 1_000_000 };

    let (s, mut r) = channel(CAPACITY);

    let th_send = thread::spawn(move || {
        block_on(async {
            for i in 0..COUNT {
                s.send(i).await.unwrap();
            }
        });
    });
    let th_recv = thread::spawn(move || {
        block_on(async {
            for i in 0..COUNT {
                assert_eq!(r.recv().await, Ok(i));
            }
        });

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

    th_send.join().unwrap();
    th_recv.join().unwrap();
}

// MPSC stress test.
#[test]
fn mpsc_stress() {
    const CAPACITY: usize = 3;
    const COUNT: usize = if cfg!(miri) { 50 } else { 1_000_000 };
    const THREADS: usize = 4;

    let (s, mut r) = channel(CAPACITY);

    let th_send = (0..THREADS).map(|_| {
        let s = s.clone();

        thread::spawn(move || {
            block_on(async {
                for i in 0..COUNT {
                    s.send(i).await.unwrap();
                }
            });
        })
    });
    let th_recv = thread::spawn(move || {
        let mut stats = Vec::new();
        stats.resize(COUNT, 0);

        block_on(async {
            for _ in 0..COUNT * THREADS {
                let i = r.recv().await.unwrap();
                stats[i] += 1;
            }
        });

        assert!(r.try_recv().is_err());

        for s in stats {
            assert_eq!(s, THREADS);
        }
    });

    for th in th_send {
        th.join().unwrap()
    }
    th_recv.join().unwrap();
}