thread_local/
thread_id.rs

1// Copyright 2017 Amanieu d'Antras
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use std::collections::BinaryHeap;
9use std::sync::Mutex;
10use std::usize;
11
12// Thread ID manager which allocates thread IDs. It attempts to aggressively
13// reuse thread IDs where possible to avoid cases where a ThreadLocal grows
14// indefinitely when it is used by many short-lived threads.
15struct 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
43// Non-zero integer which is unique to the current thread while it is running.
44// A thread ID may be reused after a thread exits.
45struct 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
58/// Returns a non-zero ID for the current thread
59pub fn get() -> usize {
60    THREAD_ID.with(|x| x.0)
61}