# Threads Local
We can use this way to fetch the current thread id.
All taking from the Smol async runtime
```rust
#[inline]
fn thread_id() -> ThreadId {
std::thread_local! {
static ID: ThreadId = thread::current().id();
}
ID.try_with(|id| *id)
.unwrap_or_else(|_| thread::current().id())
}
```
An intersting use of thread local
```rust
thread_local! {
// A queue that holds scheduled tasks.
static QUEUE: (Sender<Runnable>, Receiver<Runnable>) = flume::unbounded();
}
// Make a non-Send future.
let msg: Rc<str> = "Hello, world!".into();
let future = async move {
println!("{}", msg);
};
// A function that schedules the task when it gets woken up.
```rust
use std::future::Future;
use std::panic::catch_unwind;
use std::thread;
use async_executor::{Executor, Task};
use async_io::block_on;
use async_lock::OnceCell;
use futures_lite::future;
/// Spawns a task onto the global executor (single-threaded by default).
///
/// There is a global executor that gets lazily initialized on first use. It is included in this
/// library for convenience when writing unit tests and small programs, but it is otherwise
/// more advisable to create your own [`Executor`].
///
/// By default, the global executor is run by a single background thread, but you can also
/// configure the number of threads by setting the `SMOL_THREADS` environment variable.
///
/// Since the executor is kept around forever, `drop` is not called for tasks when the program
/// exits.
///
/// # Examples
///
/// ``
/// let task = smol::spawn(async {
/// 1 + 2
/// });
///
/// smol::block_on(async {
/// assert_eq!(task.await, 3);
/// });
/// ``
pub fn spawn<T: Send + 'static>(future: impl Future<Output = T> + Send + 'static) -> Task<T> {
static GLOBAL: OnceCell<Executor<'_>> = OnceCell::new();
fn global() -> &'static Executor<'static> {
GLOBAL.get_or_init_blocking(|| {
let num_threads = {
// Parse SMOL_THREADS or default to 1.
std::env::var("SMOL_THREADS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(1)
};
for n in 1..=num_threads {
thread::Builder::new()
.name(format!("smol-{}", n))
.spawn(|| loop {
catch_unwind(|| block_on(global().run(future::pending::<()>()))).ok();
})
.expect("cannot spawn executor thread");
}
// Prevent spawning another thread by running the process driver on this thread.
let ex = Executor::new();
#[cfg(not(target_os = "espidf"))]
ex.spawn(async_process::driver()).detach();
ex
})
}
global().spawn(future)
}
/// Number of currently active `block_on()` invocations.
static BLOCK_ON_COUNT: AtomicUsize = AtomicUsize::new(0);
/// Unparker for the "async-io" thread.
fn unparker() -> &'static parking::Unparker {
static UNPARKER: OnceCell<parking::Unparker> = OnceCell::new();
UNPARKER.get_or_init_blocking(|| {
let (parker, unparker) = parking::pair();
// Spawn a helper thread driving the reactor.
//
// Note that this thread is not exactly necessary, it's only here to help push things
// forward if there are no `Parker`s around or if `Parker`s are just idling and never
// parking.
thread::Builder::new()
.name("async-io".to_string())
.spawn(move || main_loop(parker))
.expect("cannot spawn async-io thread");
unparker
})
}
A thread registry
```rust
pub(super) struct Registry {
thread_infos: Vec<ThreadInfo>,
sleep: Sleep,
injected_jobs: Injector<JobRef>,
broadcasts: Mutex<Vec<Worker<JobRef>>>,
panic_handler: Option<Box<PanicHandler>>,
start_handler: Option<Box<StartHandler>>,
exit_handler: Option<Box<ExitHandler>>,
// When this latch reaches 0, it means that all work on this
// registry must be complete. This is ensured in the following ways:
//
// - if this is the global registry, there is a ref-count that never
// gets released.
// - if this is a user-created thread-pool, then so long as the thread-pool
// exists, it holds a reference.
// - when we inject a "blocking job" into the registry with `ThreadPool::install()`,
// no adjustment is needed; the `ThreadPool` holds the reference, and since we won't
// return until the blocking job is complete, that ref will continue to be held.
// - when `join()` or `scope()` is invoked, similarly, no adjustments are needed.
// These are always owned by some other job (e.g., one injected by `ThreadPool::install()`)
// and that job will keep the pool alive.
terminate_count: AtomicUsize,
}
/// //////////////
/// ////////////////////////////////////////////////////////////////////////
/// Initialization
static mut THE_REGISTRY: Option<Arc<Registry>> = None;
static THE_REGISTRY_SET: Once = Once::new();
/// Starts the worker threads (if that has not already happened). If
/// initialization has not already occurred, use the default
/// configuration.
pub(super) fn global_registry() -> &'static Arc<Registry> {
set_global_registry(default_global_registry)
.or_else(|err| unsafe { THE_REGISTRY.as_ref().ok_or(err) })
.expect("The global thread pool has not been initialized.")
}
/// Starts the worker threads (if that has not already happened) with
/// the given builder.
pub(super) fn init_global_registry<S>(
builder: ThreadPoolBuilder<S>,
) -> Result<&'static Arc<Registry>, ThreadPoolBuildError>
where
S: ThreadSpawn,
{
set_global_registry(|| Registry::new(builder))
}
/// Starts the worker threads (if that has not already happened)
/// by creating a registry with the given callback.
fn set_global_registry<F>(registry: F) -> Result<&'static Arc<Registry>, ThreadPoolBuildError>
where
F: FnOnce() -> Result<Arc<Registry>, ThreadPoolBuildError>,
{
let mut result = Err(ThreadPoolBuildError::new(
ErrorKind::GlobalPoolAlreadyInitialized,
));
THE_REGISTRY_SET.call_once(|| {
result = registry()
.map(|registry: Arc<Registry>| unsafe { &*THE_REGISTRY.get_or_insert(registry) })
});
result
}