wasm_safe_mutex 0.2.1

A suite of WebAssembly-safe synchronization primitives that paper over platform-specific locking constraints.
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// SPDX-License-Identifier: MIT OR Apache-2.0
use super::*;
use crate::Mutex;
use std::sync::Arc;

#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;

#[cfg(target_arch = "wasm32")]
use web_time::Duration;

use r#continue::continuation;
#[cfg(not(target_arch = "wasm32"))]
use std::thread;
#[cfg(target_arch = "wasm32")]
use wasm_safe_thread as thread;

// Configure WASM tests to run in browser (required for thread spawning)
#[cfg(all(test, target_arch = "wasm32"))]
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);

#[test_executors::async_test]
//#[cfg(not(target_arch = "wasm32"))] // HANGS on WASM
async fn test_condvar_basic_spin() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::Builder::new()
        .name("basic_spin_write".into())
        .spawn(move || {
            thread::sleep(std::time::Duration::from_millis(50));

            let (mutex, condvar) = &*pair_clone;
            let mut ready = mutex.lock_sync();
            *ready = true;
            drop(ready);
            condvar.notify_one();
            c.send(());
        })
        .unwrap();
    let (c, r2) = continuation();
    thread::Builder::new()
        .name("basic_spin_write".into())
        .spawn(move || {
            let (mutex, condvar) = &*pair;
            let mut ready = mutex.lock_sync();
            while !*ready {
                ready = condvar.wait_spin(ready);
            }
            assert!(*ready);
            c.send(());
        })
        .unwrap();
    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_block() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));

        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    });

    // Move the waiting into a worker thread
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair;
        let mut ready = mutex.lock_sync();
        while !*ready {
            ready = condvar.wait_block(ready);
        }
        assert!(*ready);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_sync() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));

        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    });

    // Move the waiting into a worker thread
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair;
        let mut ready = mutex.lock_sync();
        while !*ready {
            ready = condvar.wait_sync(ready);
        }
        assert!(*ready);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_async() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));

        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair_clone;
            let mut ready = mutex.lock_async().await;
            *ready = true;
            drop(ready);
            condvar.notify_one();
        });
        c.send(());
    });

    // Move the async waiting into a worker thread
    let (c2, r2) = continuation();
    thread::spawn(move || {
        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair;
            let mut ready = mutex.lock_async().await;
            while !*ready {
                ready = condvar.wait_async(ready).await;
            }
            assert!(*ready);
        });
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_notify_all() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let mut receivers = Vec::new();

    // Spawn 3 threads that wait for count to reach 10
    for _ in 0..3 {
        let pair = Arc::clone(&pair);
        let (c, r) = continuation();
        thread::spawn(move || {
            let (mutex, condvar) = &*pair;
            let mut count = mutex.lock_sync();
            while *count < 10 {
                count = condvar.wait_sync(count);
            }
            c.send(*count);
        });
        receivers.push(r);
    }

    // Give threads time to start waiting
    #[cfg(not(target_arch = "wasm32"))]
    thread::sleep(Duration::from_millis(50));

    // Update the count and notify all
    let (mutex, condvar) = &*pair;
    let mut count = mutex.lock_sync();
    *count = 10;
    drop(count);
    condvar.notify_all();

    // All threads should wake up and see count = 10
    for receiver in receivers {
        let result = receiver.await;
        assert_eq!(result, 10);
    }
}

#[test_executors::async_test]
async fn test_condvar_producer_consumer() {
    use std::collections::VecDeque;

    let shared = Arc::new((Mutex::new(VecDeque::new()), Condvar::new()));
    let producer = Arc::clone(&shared);

    let (c, r) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*producer;
        for i in 0..5 {
            #[cfg(not(target_arch = "wasm32"))]
            thread::sleep(Duration::from_millis(5));

            let mut queue = mutex.lock_sync();
            queue.push_back(i);
            drop(queue);
            condvar.notify_one();
        }
        c.send(());
    });

    // Move the consumer (waiting) into a worker thread
    let consumer = Arc::clone(&shared);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*consumer;
        let mut collected = Vec::new();
        for _ in 0..5 {
            let mut queue = mutex.lock_sync();
            while queue.is_empty() {
                queue = condvar.wait_sync(queue);
            }
            if let Some(value) = queue.pop_front() {
                collected.push(value);
            }
        }
        assert_eq!(collected, vec![0, 1, 2, 3, 4]);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_spin_timeout() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let (mutex, condvar) = &*pair;
    let mut ready = mutex.lock_sync();
    let deadline = Instant::now() + Duration::from_millis(10);
    let result;
    (ready, result) = condvar.wait_spin_timeout(ready, deadline);
    assert!(result.timed_out());
    assert!(!*ready);
}

#[test_executors::async_test]
async fn test_condvar_wait_spin_timeout_notified() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(50));
        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    }); // removed unwrap because thread::spawn returns JoinHandle, not Result in standard lib, but wasm_thread might be different?
    // checking wasm_thread docs or source would be good, but standard thread::spawn returns JoinHandle.
    // Wait, standard thread::spawn panics if it fails to spawn (in some impls) or returns JoinHandle.
    // Actually std::thread::Builder::spawn returns Result. std::thread::spawn returns JoinHandle.
    // So unwrap is not needed for spawn, but we should ensure it didn't panic.

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let mut ready = mutex.lock_sync();
        // Increase deadline to 5 seconds to be safe
        let deadline = Instant::now() + Duration::from_secs(5);
        while !*ready {
            let result;
            (ready, result) = condvar.wait_spin_timeout(ready, deadline);
            if result.timed_out() {
                // Add more info to panic
                panic!("Should not have timed out. Ready is still false.");
            }
        }
        assert!(*ready);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_sync_while() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));

        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    });

    let pair_waiter = Arc::clone(&pair);
    let (cw, rw) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_waiter;
        let guard = mutex.lock_sync();
        let guard = condvar.wait_sync_while(guard, |ready| !*ready);
        assert!(*guard);
        drop(guard);
        cw.send(());
    });

    r.await;
    rw.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_async_while() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));

        test_executors::spin_on(async move {
            let (mutex, condvar) = &*pair_clone;
            let mut value = mutex.lock_async().await;
            *value = 1;
            drop(value);
            condvar.notify_one();
            c.send(());
        });
    });

    let (mutex, condvar) = &*pair;
    let guard = mutex.lock_async().await;
    let guard = condvar.wait_async_while(guard, |value| *value == 0).await;
    assert_eq!(*guard, 1);
    drop(guard);

    r.await;
}

#[test_executors::async_test]
async fn test_condvar_notify_one_only_wakes_one() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let mut receivers = Vec::new();

    // Spawn 3 threads that increment on each wake
    for _ in 0..3 {
        let pair = Arc::clone(&pair);
        let (c, r) = continuation();
        thread::spawn(move || {
            let (mutex, condvar) = &*pair;
            let mut wake = mutex.lock_sync();
            while !wake.as_ref() {
                wake = condvar.wait_spin(wake);
            }
            eprintln!("Finished all wait_spins");
            c.send(());
        });
        receivers.push(r);
    }

    // Give threads time to start waiting
    #[cfg(not(target_arch = "wasm32"))]
    thread::sleep(Duration::from_millis(100));

    // Increment and notify one at a time
    for _ in 1..=3 {
        let (mutex, condvar) = &*pair;
        let mut wake = mutex.lock_sync();
        *wake = true;
        drop(wake);
        condvar.notify_one();

        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(10));
    }

    // All threads should eventually complete
    for receiver in receivers {
        receiver.await;
    }

    let (mutex, _) = &*pair;
    assert_eq!(*mutex.lock_sync(), true);
}

#[test_executors::async_test]
async fn test_condvar_wait_block_timeout() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_millis(10);
        let result;
        (ready, result) = condvar.wait_block_timeout(ready, deadline);
        assert!(result.timed_out());
        assert!(!*ready);
        c.send(());
    });

    r.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_block_timeout_notified() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let mut ready = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_secs(5);
        while !*ready {
            let result;
            (ready, result) = condvar.wait_block_timeout(ready, deadline);
            if result.timed_out() {
                panic!("Should not have timed out. Ready is still false.");
            }
        }
        assert!(*ready);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_timeout_dispatch() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        let (mutex, condvar) = &*pair_clone;
        let mut ready = mutex.lock_sync();
        *ready = true;
        drop(ready);
        condvar.notify_one();
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let mut ready = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_secs(5);
        while !*ready {
            let result;
            (ready, result) = condvar.wait_sync_timeout(ready, deadline);
            if result.timed_out() {
                panic!("Should not have timed out. Ready is still false.");
            }
        }
        assert!(*ready);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_async_timeout() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let (mutex, condvar) = &*pair;

    let mut ready = mutex.lock_async().await;
    let deadline = Instant::now() + Duration::from_millis(50);
    let result;
    (ready, result) = condvar.wait_async_timeout(ready, deadline).await;
    assert!(result.timed_out());
    assert!(!*ready);
}

#[test_executors::async_test]
async fn test_condvar_wait_async_timeout_notified() {
    let pair = Arc::new((Mutex::new(false), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair_clone;
            let mut ready = mutex.lock_async().await;
            *ready = true;
            drop(ready);
            condvar.notify_one();
        });
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair_clone2;
            let mut ready = mutex.lock_async().await;
            let deadline = Instant::now() + Duration::from_secs(5);
            while !*ready {
                let result;
                (ready, result) = condvar.wait_async_timeout(ready, deadline).await;
                if result.timed_out() {
                    panic!("Should not have timed out. Ready is still false.");
                }
            }
            assert!(*ready);
        });
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_async_timeout_while() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair_clone;
            let mut value = mutex.lock_async().await;
            *value = 10;
            drop(value);
            condvar.notify_one();
        });
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        test_executors::spin_on(async {
            let (mutex, condvar) = &*pair_clone2;
            let guard = mutex.lock_async().await;
            let deadline = Instant::now() + Duration::from_secs(5);
            let (guard, result) = condvar
                .wait_async_timeout_while(guard, deadline, |value| *value < 10)
                .await;
            assert!(!result.timed_out());
            assert_eq!(*guard, 10);
        });
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_spin_timeout_while() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        thread::sleep(std::time::Duration::from_millis(50));
        let (mutex, condvar) = &*pair_clone;
        let mut value = mutex.lock_sync();
        *value = 10;
        drop(value);
        condvar.notify_one();
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let guard = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_secs(5);
        let (guard, result) = condvar.wait_spin_timeout_while(guard, deadline, |v| *v < 10);
        assert!(!result.timed_out());
        assert_eq!(*guard, 10);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_block_timeout_while() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        let (mutex, condvar) = &*pair_clone;
        let mut value = mutex.lock_sync();
        *value = 10;
        drop(value);
        condvar.notify_one();
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let guard = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_secs(5);
        let (guard, result) = condvar.wait_block_timeout_while(guard, deadline, |v| *v < 10);
        assert!(!result.timed_out());
        assert_eq!(*guard, 10);
        c2.send(());
    });

    r.await;
    r2.await;
}

#[test_executors::async_test]
async fn test_condvar_wait_sync_timeout_while() {
    let pair = Arc::new((Mutex::new(0), Condvar::new()));
    let pair_clone = Arc::clone(&pair);

    let (c, r) = continuation();
    thread::spawn(move || {
        #[cfg(not(target_arch = "wasm32"))]
        thread::sleep(Duration::from_millis(50));

        let (mutex, condvar) = &*pair_clone;
        let mut value = mutex.lock_sync();
        *value = 10;
        drop(value);
        condvar.notify_one();
        c.send(());
    });

    let pair_clone2 = Arc::clone(&pair);
    let (c2, r2) = continuation();
    thread::spawn(move || {
        let (mutex, condvar) = &*pair_clone2;
        let guard = mutex.lock_sync();
        let deadline = Instant::now() + Duration::from_secs(5);
        let (guard, result) = condvar.wait_sync_timeout_while(guard, deadline, |v| *v < 10);
        assert!(!result.timed_out());
        assert_eq!(*guard, 10);
        c2.send(());
    });

    r.await;
    r2.await;
}