thread_local/
thread_id.rs1use std::collections::BinaryHeap;
9use std::sync::Mutex;
10use std::usize;
11
12struct ThreadIdManager {
16 limit: usize,
17 free_list: BinaryHeap<usize>,
18}
19impl ThreadIdManager {
20 fn new() -> ThreadIdManager {
21 ThreadIdManager {
22 limit: usize::MAX,
23 free_list: BinaryHeap::new(),
24 }
25 }
26 fn alloc(&mut self) -> usize {
27 if let Some(id) = self.free_list.pop() {
28 id
29 } else {
30 let id = self.limit;
31 self.limit = self.limit.checked_sub(1).expect("Ran out of thread IDs");
32 id
33 }
34 }
35 fn free(&mut self, id: usize) {
36 self.free_list.push(id);
37 }
38}
39lazy_static! {
40 static ref THREAD_ID_MANAGER: Mutex<ThreadIdManager> = Mutex::new(ThreadIdManager::new());
41}
42
43struct ThreadId(usize);
46impl ThreadId {
47 fn new() -> ThreadId {
48 ThreadId(THREAD_ID_MANAGER.lock().unwrap().alloc())
49 }
50}
51impl Drop for ThreadId {
52 fn drop(&mut self) {
53 THREAD_ID_MANAGER.lock().unwrap().free(self.0);
54 }
55}
56thread_local!(static THREAD_ID: ThreadId = ThreadId::new());
57
58pub fn get() -> usize {
60 THREAD_ID.with(|x| x.0)
61}