Skip to content

Commit c77979b

Browse files
committed
Fix for thread locals
1 parent 4edcddf commit c77979b

File tree

1 file changed

+24
-15
lines changed

1 file changed

+24
-15
lines changed

src/libstd/sys/redox/thread_local.rs

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,27 @@
1212

1313
use collections::BTreeMap;
1414
use ptr;
15+
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
1516

1617
pub type Key = usize;
1718

1819
type Dtor = unsafe extern fn(*mut u8);
1920

20-
#[thread_local]
21-
static mut NEXT_KEY: Key = 0;
21+
static NEXT_KEY: AtomicUsize = ATOMIC_USIZE_INIT;
22+
23+
static mut KEYS: *mut BTreeMap<Key, Option<Dtor>> = ptr::null_mut();
2224

2325
#[thread_local]
24-
static mut LOCALS: *mut BTreeMap<Key, (*mut u8, Option<Dtor>)> = ptr::null_mut();
26+
static mut LOCALS: *mut BTreeMap<Key, *mut u8> = ptr::null_mut();
27+
28+
unsafe fn keys() -> &'static mut BTreeMap<Key, Option<Dtor>> {
29+
if KEYS == ptr::null_mut() {
30+
KEYS = Box::into_raw(Box::new(BTreeMap::new()));
31+
}
32+
&mut *KEYS
33+
}
2534

26-
unsafe fn locals() -> &'static mut BTreeMap<Key, (*mut u8, Option<Dtor>)> {
35+
unsafe fn locals() -> &'static mut BTreeMap<Key, *mut u8> {
2736
if LOCALS == ptr::null_mut() {
2837
LOCALS = Box::into_raw(Box::new(BTreeMap::new()));
2938
}
@@ -32,26 +41,26 @@ unsafe fn locals() -> &'static mut BTreeMap<Key, (*mut u8, Option<Dtor>)> {
3241

3342
#[inline]
3443
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
35-
let key = NEXT_KEY;
36-
NEXT_KEY += 1;
37-
locals().insert(key, (0 as *mut u8, dtor));
44+
let key = NEXT_KEY.fetch_add(1, Ordering::SeqCst);
45+
keys().insert(key, dtor);
3846
key
3947
}
4048

4149
#[inline]
42-
pub unsafe fn set(key: Key, value: *mut u8) {
43-
locals().get_mut(&key).unwrap().0 = value;
50+
pub unsafe fn get(key: Key) -> *mut u8 {
51+
if let Some(&entry) = locals().get(&key) {
52+
entry
53+
} else {
54+
ptr::null_mut()
55+
}
4456
}
4557

4658
#[inline]
47-
pub unsafe fn get(key: Key) -> *mut u8 {
48-
locals()[&key].0
59+
pub unsafe fn set(key: Key, value: *mut u8) {
60+
locals().insert(key, value);
4961
}
5062

5163
#[inline]
5264
pub unsafe fn destroy(key: Key) {
53-
let (value, dtor) = locals().remove(&key).unwrap();
54-
if let Some(dtor_fn) = dtor {
55-
dtor_fn(value);
56-
}
65+
keys().remove(&key);
5766
}

0 commit comments

Comments
 (0)