Skip to content

Commit fa2f5d6

Browse files
committed
Use the thread_local crate for local dicts
1 parent 87a11fc commit fa2f5d6

File tree

3 files changed

+7
-19
lines changed

3 files changed

+7
-19
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

vm/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ bstr = "0.2.12"
7272
crossbeam-utils = "0.7"
7373
generational-arena = "0.2"
7474
parking_lot = { git = "https://github.com/Amanieu/parking_lot" } # TODO: use published version
75+
thread_local = "1.0"
7576

7677
## unicode stuff
7778
unicode_names2 = "0.4"

vm/src/stdlib/thread.rs

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,13 @@ use crate::pyobject::{
1111
};
1212
use crate::vm::VirtualMachine;
1313

14-
use crossbeam_utils::atomic::AtomicCell;
1514
use parking_lot::{
1615
lock_api::{RawMutex as RawMutexT, RawMutexTimed, RawReentrantMutex},
1716
RawMutex, RawThreadId,
1817
};
18+
use thread_local::ThreadLocal;
19+
1920
use std::cell::RefCell;
20-
use std::collections::HashMap;
2121
use std::io::Write;
2222
use std::time::Duration;
2323
use std::{fmt, thread};
@@ -267,13 +267,10 @@ fn thread_count(vm: &VirtualMachine) -> usize {
267267
vm.state.thread_count.load()
268268
}
269269

270-
static LOCAL_DATA_KEY: AtomicCell<usize> = AtomicCell::new(0);
271-
thread_local!(static LOCAL_DATA: RefCell<HashMap<usize, PyDictRef>> = RefCell::default());
272-
273270
#[pyclass(name = "_local")]
274271
#[derive(Debug)]
275272
struct PyLocal {
276-
key: usize,
273+
data: ThreadLocal<PyDictRef>,
277274
}
278275

279276
impl PyValue for PyLocal {
@@ -282,27 +279,16 @@ impl PyValue for PyLocal {
282279
}
283280
}
284281

285-
impl Drop for PyLocal {
286-
fn drop(&mut self) {
287-
LOCAL_DATA.with(|map| map.borrow_mut().remove(&self.key));
288-
}
289-
}
290-
291282
#[pyimpl(flags(BASETYPE))]
292283
impl PyLocal {
293284
fn ldict(&self, vm: &VirtualMachine) -> PyDictRef {
294-
LOCAL_DATA.with(|map| {
295-
map.borrow_mut()
296-
.entry(self.key)
297-
.or_insert_with(|| vm.ctx.new_dict())
298-
.clone()
299-
})
285+
self.data.get_or(|| vm.ctx.new_dict()).clone()
300286
}
301287

302288
#[pyslot]
303289
fn tp_new(cls: PyClassRef, _args: PyFuncArgs, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
304290
PyLocal {
305-
key: LOCAL_DATA_KEY.fetch_add(1),
291+
data: ThreadLocal::new(),
306292
}
307293
.into_ref_with_type(vm, cls)
308294
}

0 commit comments

Comments
 (0)