1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
//! 线程本地存储
#![unstable(feature = "thread_local_internals", issue = "none")]
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
#[cfg(test)]
mod dynamic_tests;
use crate::error::Error;
use crate::fmt;
/// 拥有其内容的线程本地存储密钥。
///
/// 该密钥使用可用于目标平台的最快速度的实现。它用 [`thread_local!`] 宏实例化,主要方法是 [`with`] 方法。
///
/// [`with`] 方法产生对所包含值的引用,该引用不能跨线程发送或转义给定的闭包。
///
/// # 初始化与销毁
///
/// 初始化是在线程中对 [`with`] 的第一次调用中动态执行的,并且当线程退出时,实现 [`Drop`] 的值将被销毁。一些注意事项适用,下面将进行说明。
///
/// LocalKey 的初始化不能递归地依赖于它自己,以这种方式使用 `LocalKey` 会使初始化在第一次调用 `with` 时无限递归。
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
/// use std::thread;
///
/// thread_local!(static FOO: RefCell<u32> = RefCell::new(1));
///
/// FOO.with(|f| {
/// assert_eq!(*f.borrow(), 1);
/// *f.borrow_mut() = 2;
/// });
///
/// // 每个线程以 1 的初始值开始
/// let t = thread::spawn(move|| {
/// FOO.with(|f| {
/// assert_eq!(*f.borrow(), 1);
/// *f.borrow_mut() = 3;
/// });
/// });
///
/// // 等待线程完成并在 panic 上退出
/// t.join().unwrap();
///
/// // 尽管有子线程,我们仍保留原始值 2
/// FOO.with(|f| {
/// assert_eq!(*f.borrow(), 2);
/// });
/// ```
///
/// # 特定于平台的行为
///
/// 请注意,我们尽了 "最大努力" 来确保运行线程本地存储中存储的类型的析构函数,但并非所有平台都能保证运行线程本地存储中所有类型的析构函数。
///
/// 例如,有许多已知的警告未运行析构函数:
///
/// 1. 在 Unix 系统上,当使用基于 pthread 的 TLS 时,主线程退出时,不会为主线程上的 TLS 值运行析构函数。
/// 请注意,应用程序也将在主线程退出后立即退出。
/// 2. 在所有平台上,TLS 都有可能在销毁期间重新初始化其他 TLS 插槽。
/// 某些平台通过防止重新初始化已销毁的任何插槽来确保不会无限发生这种情况,但并非所有平台都具有此保护措施。
/// 那些不受约束的平台通常具有综合限制,在此之后,将不再运行析构函数。
/// 3. 当进程在 Windows 系统上退出时,TLS 析构函数可能只在导致进程退出的线程上运行。这是因为其他线程可能会被强制终止。
///
/// ## 线程本地析构函数中的同步
///
/// 在 Windows 上,线程本地析构函数中的同步操作 (例如 [`JoinHandle::join`]) 容易出现死锁,因此应该避免。
/// 这是因为 [loader lock] 在运行析构函数时,仍被持有。每当线程启动、退出、加载或卸载 DLL 时,都会获取锁。
/// 所以,只要线程本地析构函数正在运行,这些事件就会被阻止。
///
/// [loader lock]: https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices
/// [`JoinHandle::join`]: crate::thread::JoinHandle::join
/// [`with`]: LocalKey::with
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub struct LocalKey<T: 'static> {
// 这种外部 `LocalKey<T>` 类型将存储在静态变量中,但是内部的实际数据有时会用 #[thread_local] 标记。
// 引用 #[thread_local] 静态变量对真实的静态变量是无效的,因此我们通过在函数间接层 (此重击) 中公开一个访问器来解决此问题。
//
// 请注意,该重击本身是不安全的,因为返回的数据所在的插槽 `'static` 的生命周期实际上是无效的。
// 此处的生命周期实际上比当前正在运行的线程短一些!
//
// 尽管这是一个间接的额外层,但是从理论上讲,LLVM 应该可以对其进行虚拟化,因为 `inner` 的值永远不会更改,并且常量在 crate 内应为只读。
//
// 仅当在 crates 上导出 TLS 静态信息时,这才主要遇到问题。
//
//
//
//
//
inner: unsafe fn() -> Option<&'static T>,
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T: 'static> fmt::Debug for LocalKey<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("LocalKey").finish_non_exhaustive()
}
}
/// 声明一个新的 [`std::thread::LocalKey`] 类型的线程本地存储密钥。
///
/// # Syntax
///
/// 宏可以包装任意数量的静态声明,并使它们成为局部线程。
///
/// 允许每个静态的公开和属性。Example:
///
/// ```
/// use std::cell::RefCell;
/// thread_local! {
/// pub static FOO: RefCell<u32> = RefCell::new(1);
///
/// #[allow(unused)]
/// static BAR: RefCell<f32> = RefCell::new(1.0);
/// }
/// # fn main() {}
/// ```
///
/// 有关更多信息,请参见 [`LocalKey` 文档][`std::thread::LocalKey`]。
///
/// [`std::thread::LocalKey`]: crate::thread::LocalKey
#[macro_export]
#[stable(feature = "rust1", since = "1.0.0")]
#[allow_internal_unstable(thread_local_internals)]
macro_rules! thread_local {
// 空 (递归的基本情况)
() => {};
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }; $($rest:tt)*) => (
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
$crate::thread_local!($($rest)*);
);
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = const { $init:expr }) => (
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, const $init);
);
// 处理多个声明
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => (
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
$crate::thread_local!($($rest)*);
);
// 处理一个声明
($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => (
$crate::__thread_local_inner!($(#[$attr])* $vis $name, $t, $init);
);
}
#[doc(hidden)]
#[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")]
#[macro_export]
#[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)]
#[allow_internal_unsafe]
macro_rules! __thread_local_inner {
// 用于为常量初始化的线程局部变量生成 `LocalKey` 值
(@key $t:ty, const $init:expr) => {{
#[cfg_attr(not(windows), inline)] // 请参见下面的注释
unsafe fn __getit() -> $crate::option::Option<&'static $t> {
const INIT_EXPR: $t = $init;
// 没有原子的 wasm 直接映射到 `static mut`,并且没有实现 dtor,因为线程 dtor 现在在 wasm 上还不是一个真正的东西
//
//
// FIXME(#84224) 这应该在 `target_thread_local` 块之后。
//
//
#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
{
static mut VAL: $t = INIT_EXPR;
Some(&VAL)
}
// 如果平台支持 `#[thread_local]`,请使用它。
#[cfg(all(
target_thread_local,
not(all(target_family = "wasm", not(target_feature = "atomics"))),
))]
{
#[thread_local]
static mut VAL: $t = INIT_EXPR;
// 如果不需要 dtor,我们可以做一些 "非常原始" 的事情,然后开始。
//
if !$crate::mem::needs_drop::<$t>() {
unsafe {
return Some(&VAL)
}
}
// 0 == dtor 未注册
// 1 == dtor 已注册,dtor 未运行
// 2 == dtor 已注册并正在运行或已运行
#[thread_local]
static mut STATE: u8 = 0;
unsafe extern "C" fn destroy(ptr: *mut u8) {
let ptr = ptr as *mut $t;
unsafe {
debug_assert_eq!(STATE, 1);
STATE = 2;
$crate::ptr::drop_in_place(ptr);
}
}
unsafe {
match STATE {
// 0 == 我们还没有注册析构函数,所以现在注册。
//
0 => {
$crate::thread::__FastLocalKeyInner::<$t>::register_dtor(
$crate::ptr::addr_of_mut!(VAL) as *mut u8,
destroy,
);
STATE = 1;
Some(&VAL)
}
// 1 == 析构函数已注册且值有效,因此返回指针。
//
1 => Some(&VAL),
// 否则析构函数已经运行,所以我们不能授予访问权限。
//
_ => None,
}
}
}
// 在没有 `#[thread_local]` 的平台上,我们回退到与下面的 os 线程局部变量相同的实现。
//
#[cfg(all(
not(target_thread_local),
not(all(target_family = "wasm", not(target_feature = "atomics"))),
))]
{
#[inline]
const fn __init() -> $t { INIT_EXPR }
static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
$crate::thread::__OsLocalKeyInner::new();
#[allow(unused_unsafe)]
unsafe { __KEY.get(__init) }
}
}
unsafe {
$crate::thread::LocalKey::new(__getit)
}
}};
// 用于为 `thread_local!` 生成 `LocalKey` 值
(@key $t:ty, $init:expr) => {
{
#[inline]
fn __init() -> $t { $init }
// 在阅读这个函数时,您可能会问 "为什么除了 Windows 之外,其他地方都内联这个函数?",这是一个非常合理的问题。
// 简而言之,如果这个函数是内联的,它会导致 rustc 段错误。
// 更长的故事是 Windows 看起来不支持跨 DLL 边界的线程局部变量的 `extern` 引用。
// 这似乎至少在 LLVM 实现的 ABI 中不受支持。
//
// 正因为如此,我们从不在 Windows 上内联,但我们在其他平台上内联 (在这些平台上,跨 dll 的线程局部变量的外部引用是受支持的)。
// 一个更好的解决方法是在 Windows 上内联这个函数,但仅限于 "静态链接" 组件。
// 例如,如果两个单独编译的 rlib 最终链接到一个 DLL 中,那么可以跨边界内联这个函数。
// 跨 DLL 边界内联这个函数是不好的。
// 不幸的是,rustc 目前在属性中没有这种可用的逻辑,而且还不清楚 rustc 是否有能力回答这个问题 (这更像是 Cargo 问题)。
//
// 这意味着,不幸的是,Windows 现在的路径很悲观,它从来没有内联。
//
// "有时应该在 Windows 上启用" 的问题是 #84933
//
//
//
//
//
//
//
//
#[cfg_attr(not(windows), inline)]
unsafe fn __getit() -> $crate::option::Option<&'static $t> {
#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
static __KEY: $crate::thread::__StaticLocalKeyInner<$t> =
$crate::thread::__StaticLocalKeyInner::new();
#[thread_local]
#[cfg(all(
target_thread_local,
not(all(target_family = "wasm", not(target_feature = "atomics"))),
))]
static __KEY: $crate::thread::__FastLocalKeyInner<$t> =
$crate::thread::__FastLocalKeyInner::new();
#[cfg(all(
not(target_thread_local),
not(all(target_family = "wasm", not(target_feature = "atomics"))),
))]
static __KEY: $crate::thread::__OsLocalKeyInner<$t> =
$crate::thread::__OsLocalKeyInner::new();
// FIXME: 当宏不再对丢失/额外不安全块发出警告时,请删除 #[allow(...)] 标记。
// See https://github.com/rust-lang/rust/issues/74838.
//
#[allow(unused_unsafe)]
unsafe { __KEY.get(__init) }
}
unsafe {
$crate::thread::LocalKey::new(__getit)
}
}
};
($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => {
$(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> =
$crate::__thread_local_inner!(@key $t, $($init)*);
}
}
/// [`LocalKey::try_with`](struct.LocalKey.html#method.try_with) 返回的错误。
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
#[non_exhaustive]
#[derive(Clone, Copy, Eq, PartialEq)]
pub struct AccessError;
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl fmt::Debug for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AccessError").finish()
}
}
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl fmt::Display for AccessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt("already destroyed", f)
}
}
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
impl Error for AccessError {}
impl<T: 'static> LocalKey<T> {
#[doc(hidden)]
#[unstable(
feature = "thread_local_internals",
reason = "recently added to create a key",
issue = "none"
)]
#[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
pub const unsafe fn new(inner: unsafe fn() -> Option<&'static T>) -> LocalKey<T> {
LocalKey { inner }
}
/// 获取对此 TLS 密钥中的值的引用。
///
/// 如果此线程尚未引用此键,则将延迟地初始化该值。
///
/// # Panics
///
/// 如果该键当前正在运行其析构函数,则此函数将为 `panic!()`; 如果先前已为此线程运行了析构函数,则它可能 panic。
///
///
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with<F, R>(&'static self, f: F) -> R
where
F: FnOnce(&T) -> R,
{
self.try_with(f).expect(
"cannot access a Thread Local Storage value \
during or after destruction",
)
}
/// 获取对此 TLS 密钥中的值的引用。
///
/// 如果此线程尚未引用此键,则将延迟地初始化该值。
/// 如果密钥已被销毁 (如果在析构函数中调用它可能会发生这种情况),此函数将返回 [`AccessError`]。
///
///
/// # Panics
///
/// 如果未初始化密钥并且密钥的初始化 panics,则此函数仍将 `panic!()`。
///
#[stable(feature = "thread_local_try_with", since = "1.26.0")]
#[inline]
pub fn try_with<F, R>(&'static self, f: F) -> Result<R, AccessError>
where
F: FnOnce(&T) -> R,
{
unsafe {
let thread_local = (self.inner)().ok_or(AccessError)?;
Ok(f(thread_local))
}
}
}
mod lazy {
use crate::cell::UnsafeCell;
use crate::hint;
use crate::mem;
pub struct LazyKeyInner<T> {
inner: UnsafeCell<Option<T>>,
}
impl<T> LazyKeyInner<T> {
pub const fn new() -> LazyKeyInner<T> {
LazyKeyInner { inner: UnsafeCell::new(None) }
}
pub unsafe fn get(&self) -> Option<&'static T> {
// SAFETY: 调用者必须确保绝不向内部 cell 传递任何引用,也不要向所述 cell 内部的 Option<T> 进行可变引用。
// 尽管'static 的生命周期本身是不安全的,这使 get 方法变得不安全,但这使引用变得安全。
//
//
unsafe { (*self.inner.get()).as_ref() }
}
/// 调用者必须确保没有激活引用:此方法需要唯一的访问权限。
///
pub unsafe fn initialize<F: FnOnce() -> T>(&self, init: F) -> &'static T {
// 预先执行初始化,然后将其移动到我们的插槽中,以防万一初始化失败。
//
let value = init();
let ptr = self.inner.get();
// SAFETY:
//
// 请注意,从理论上讲,它只能是 `*ptr = Some(value)`,但是由于编译器当前将使用类似以下内容的代码生成该模式:
//
// ptr::drop_in_place(ptr)
// ptr::write(ptr, Some(value))
//
// 由于这种模式,`ptr` 中的值的析构函数有可能重新访问 TLS (例如,如果正在递归初始化),在这种情况下,将有一个指向相同值的 `&` 和 `&mut` 指针 (违反别名)。
// 为了避免设置 "我正在运行析构函数" 标志,我们只使用 `mem::replace`,它应该以稍微不同的方式对操作进行排序,并确保调用安全。
//
// 前提条件还确保了我们是目前唯一访问 `self` 的计算机,因此可以很好地进行替换。
//
//
//
//
//
//
unsafe {
let _ = mem::replace(&mut *ptr, Some(value));
}
// SAFETY: 通过调用 `mem::replace`,可以确保 `ptr` 后面有一个 `Some`,而不是 `None`,因此将永远无法到达 `unreachable_unchecked`。
//
//
unsafe {
// 存储 `Some` 之后,我们想对刚刚存储的内容进行引用。
// 尽管我们可以在这里使用 `unwrap`,并且它应该始终有效,但是根据经验,似乎并没有总是对其进行优化,这意味着使用 `try_with` 之类的东西可能会引入 panic 代码并导致大规模的膨胀。
//
//
//
match *ptr {
Some(ref x) => x,
None => hint::unreachable_unchecked(),
}
}
}
/// 其他方法在取 &self 时分发引用。
/// 因此,此方法的调用者必须确保没有 `&` 和 `&mut` 同时可用和使用。
///
#[allow(unused)]
pub unsafe fn take(&mut self) -> Option<T> {
// SAFETY: 有关此方法,请参见文档注释。
unsafe { (*self.inner.get()).take() }
}
}
}
/// 在像 wasm 这样的一些目标上没有线程,所以不需要生成线程局部变量,我们可以只使用普通的静态变量!
///
#[doc(hidden)]
#[cfg(all(target_family = "wasm", not(target_feature = "atomics")))]
pub mod statik {
use super::lazy::LazyKeyInner;
use crate::fmt;
pub struct Key<T> {
inner: LazyKeyInner<T>,
}
unsafe impl<T> Sync for Key<T> {}
impl<T> fmt::Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").finish_non_exhaustive()
}
}
impl<T> Key<T> {
pub const fn new() -> Key<T> {
Key { inner: LazyKeyInner::new() }
}
pub unsafe fn get(&self, init: fn() -> T) -> Option<&'static T> {
// SAFETY: 调用者必须确保绝不向内部 cell 传递任何引用,也不要向所述 cell 内部的 Option<T> 进行可变引用。
// 尽管'static 的生命周期本身是不安全的,这使 get 方法变得不安全,但这使引用变得安全。
//
//
let value = unsafe {
match self.inner.get() {
Some(ref value) => value,
None => self.inner.initialize(init),
}
};
Some(value)
}
}
}
#[doc(hidden)]
#[cfg(target_thread_local)]
pub mod fast {
use super::lazy::LazyKeyInner;
use crate::cell::Cell;
use crate::fmt;
use crate::mem;
use crate::sys::thread_local_dtor::register_dtor;
#[derive(Copy, Clone)]
enum DtorState {
Unregistered,
Registered,
RunningOrHasRun,
}
// 此数据结构体经过精心构造,因此快速路径仅包含 x86 上的一个分支。
// 为了避免在 OSX 上重复查找 tls,必须进行优化。
//
// LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
//
pub struct Key<T> {
// 如果 `LazyKeyInner::get` 返回 `None`,则表明:
// * 该值从未初始化
// * 该值正在递归初始化
// * 该值已被销毁或正在被销毁。要确定哪种 `None`,请检查 `dtor_state`。
//
//
// 这对快速路径非常优化,它非常友好 - 已初始化但尚未丢弃。
//
inner: LazyKeyInner<T>,
// 跟踪析构函数状态的元数据。
// 请记住,此变量是线程局部的,而不是局部的。
dtor_state: Cell<DtorState>,
}
impl<T> fmt::Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").finish_non_exhaustive()
}
}
impl<T> Key<T> {
pub const fn new() -> Key<T> {
Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
}
// 请注意,这只是一个可公开调用的函数,仅适用于线程局部变量的常量初始化形式,基本上是调用 libstd 中其他地方定义的 free `register_dtor` 函数的一种方式。
//
//
pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
unsafe {
register_dtor(a, dtor);
}
}
pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
// SAFETY: 有关详细信息,请参见 `LazyKeyInner::get` 和 `try_initialize` 的定义。
//
// 调用者必须确保在调用此内部 cell 或内部 T 时永远不会对它起作用。
//
// `try_initialize` 为此而依赖于传递的 `init` 函数。
//
//
unsafe {
match self.inner.get() {
Some(val) => Some(val),
None => self.try_initialize(init),
}
}
}
// 每个快速线程局部变量只调用一次 `try_initialize`,除非在 thread_local dtor 引用其他 thread_local 的极端情况下,或者它正在被递归初始化。
//
//
// Macos: 内联这个函数会导致每个调用到 `Key::get` 时执行两次 `tlv_get_addr` 调用。
// LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722
//
//
#[inline(never)]
unsafe fn try_initialize<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
// SAFETY: 请参见上面的注释 (此函数文档)。
if !mem::needs_drop::<T>() || unsafe { self.try_register_dtor() } {
// SAFETY: 请参见上面的注释 (他的函数 doc)。
Some(unsafe { self.inner.initialize(init) })
} else {
None
}
}
// 每个快速线程局部变量只调用一次 `try_register_dtor`,除非在 thread_local dtor 引用其他 thread_local 的极端情况下,或者它正在被递归初始化。
//
//
unsafe fn try_register_dtor(&self) -> bool {
match self.dtor_state.get() {
DtorState::Unregistered => {
// SAFETY: dtor 注册发生在初始化之前。
// 使用 `destroy_value<T>` 时将 `self` 作为指针传递是安全的,因为函数将建立指向 Key<T> 的指针,Key<T> 是 self 的类型,因此可以找到正确的大小。
//
//
//
unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::<T>) };
self.dtor_state.set(DtorState::Registered);
true
}
DtorState::Registered => {
// 递归初始化
true
}
DtorState::RunningOrHasRun => false,
}
}
}
unsafe extern "C" fn destroy_value<T>(ptr: *mut u8) {
let ptr = ptr as *mut Key<T>;
// SAFETY:
//
// 指针 `ptr` 刚好在上面构建,并且来自 `try_register_dtor`,它最初是 `self` 的 Key<T>,使其成为非 NUL 且类型正确。
//
//
// 在运行用户析构函数之前,请确保将 `Option<T>` 设置为 `None`,将 `dtor_state` 设置为 `RunningOrHasRun`。
// 这将导致对 `get` 的 future 调用再次运行 `try_initialize_drop`,该操作现在将失败,并返回 `None`。
//
//
//
unsafe {
let value = (*ptr).inner.take();
(*ptr).dtor_state.set(DtorState::RunningOrHasRun);
drop(value);
}
}
}
#[doc(hidden)]
pub mod os {
use super::lazy::LazyKeyInner;
use crate::cell::Cell;
use crate::fmt;
use crate::marker;
use crate::ptr;
use crate::sys_common::thread_local_key::StaticKey as OsStaticKey;
pub struct Key<T> {
// 我们将用于注销的 OS-TLS 密钥。
os: OsStaticKey,
marker: marker::PhantomData<Cell<T>>,
}
impl<T> fmt::Debug for Key<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").finish_non_exhaustive()
}
}
unsafe impl<T> Sync for Key<T> {}
struct Value<T: 'static> {
inner: LazyKeyInner<T>,
key: &'static Key<T>,
}
impl<T: 'static> Key<T> {
#[rustc_const_unstable(feature = "thread_local_internals", issue = "none")]
pub const fn new() -> Key<T> {
Key { os: OsStaticKey::new(Some(destroy_value::<T>)), marker: marker::PhantomData }
}
/// 要求调用者确保在调用此方法时没有激活任何可变引用。
///
pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> {
// SAFETY: 请参见此方法的文档。
let ptr = unsafe { self.os.get() as *mut Value<T> };
if ptr as usize > 1 {
// SAFETY: 检查确保指针是安全的 (其析构函数未运行) + 它来自受信任的源 (self)。
//
if let Some(ref value) = unsafe { (*ptr).inner.get() } {
return Some(value);
}
}
// SAFETY: 在这一点上,我们确定我们没有任何值,因此初始化 (或尝试进行) 是安全的。
//
unsafe { self.try_initialize(init) }
}
// `try_initialize` 每个 os 线程局部变量只调用一次,除非在 thread_local dtor 引用其他 thread_local 的极端情况下,或者它正在被递归初始化。
//
//
unsafe fn try_initialize(&'static self, init: fn() -> T) -> Option<&'static T> {
// SAFETY: 没有派发任何可变引用,这意味着获得值是可以的。
//
let ptr = unsafe { self.os.get() as *mut Value<T> };
if ptr as usize == 1 {
// 析构函数正在运行
return None;
}
let ptr = if ptr.is_null() {
// 如果查找返回 null,则表明我们尚未初始化自己的本地副本,因此请立即进行初始化。
//
let ptr: Box<Value<T>> = box Value { inner: LazyKeyInner::new(), key: self };
let ptr = Box::into_raw(ptr);
// SAFETY: 在这一点上,我们确定 ptr 内没有任何值,因此设置它不会影响任何其他人。
//
unsafe {
self.os.set(ptr as *mut u8);
}
ptr
} else {
// 递归初始化
ptr
};
// SAFETY: 已确保 ptr 为非 NUL 且正好位于 a 以上,因此可以安全地解引用。
//
unsafe { Some((*ptr).inner.initialize(init)) }
}
}
unsafe extern "C" fn destroy_value<T: 'static>(ptr: *mut u8) {
// SAFETY:
//
// 当这个析构函数开始运行时,OS TLS 确保这个键包含一个空值。
// 我们将其设置回哨兵值 1,以确保对该线程的 `get` 的任何 future 调用都将返回 `None`。
//
//
// 请注意,为防止无限循环,我们在自己从析构函数返回之前就将其重置为 null。
//
//
unsafe {
let ptr = Box::from_raw(ptr as *mut Value<T>);
let key = ptr.key;
key.os.set(1 as *mut u8);
drop(ptr);
key.os.set(ptr::null_mut());
}
}
}