Browse Source

Add Sync and Send, add tsan test.

Vadzim Dambrouski 4 years ago
parent
commit
a469e10347
2 changed files with 20 additions and 0 deletions
  1. 12 0
      examples/thread_sanitizer.rs
  2. 8 0
      src/lib.rs

+ 12 - 0
examples/thread_sanitizer.rs

@@ -0,0 +1,12 @@
+use nostd_cell::OnceCell;
+use std::thread;
+
+static C: OnceCell<u32> = OnceCell::new();
+
+fn main() {
+    let t1 = thread::spawn(|| {
+        C.set(11).ok();
+    });
+    C.set(34).ok();
+    t1.join().unwrap();
+}

+ 8 - 0
src/lib.rs

@@ -10,6 +10,14 @@ use core::{
     sync::atomic::{AtomicU8, Ordering},
 };
 
+// Why do we need `T: Send`?
+// Thread A creates a `OnceCell` and shares it with
+// scoped thread B, which fills the cell, which is
+// then destroyed by A. That is, destructor observes
+// a sent value.
+unsafe impl<T: Sync + Send> Sync for OnceCell<T> {}
+unsafe impl<T: Send> Send for OnceCell<T> {}
+
 // Three states that a OnceCell can be in, encoded into the lower bits of `state` in
 // the OnceCell structure.
 const INCOMPLETE: u8 = 0x0;