前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Rust 中 #[thread_local] 的drop方法不被调用

Rust 中 #[thread_local] 的drop方法不被调用

作者头像
drdrxp
发布2023-02-20 16:44:27
1.1K0
发布2023-02-20 16:44:27
举报

原文链接: https://drmingdrmer.github.io/tips/#/page/rust-thread-local-drop

Rust 中有2种方法声明 thread-local[2] 变量: 使用标准库的宏 thread_local!{}[3] 或使用 attribute #[thread_local][4], 经在databend的好友 winter[5], 提醒, 这里有个不rust的地方, #[thread_local] 按官方说法是被"translates directly to the thread_local attribute in LLVM", 线程销毁时不会调用它的drop方法, 但宏声明的thread-local变量没问题:

使用宏 thread_local!{...} 定义, 正常调用了 drop:

代码语言:javascript
复制
struct Foo(usize);
impl Drop for Foo {
    fn drop(&mut self) { println!("dropped"); }
}

thread_local! {
    static MACRO_TLS: std::cell::RefCell<Foo> = std::cell::RefCell::new(Foo(0));
}

fn main() {
    let _ = std::thread::spawn(|| unsafe {
        MACRO_TLS.with(|f| {
            println!("foo: {}", f.borrow_mut().0);
        });
    })
    .join();
}
// Output:
// foo: 0
// dropped

使用 attribute #[thread_local] 定义, 没有调用 drop:

代码语言:javascript
复制
#![feature(thread_local)]
struct Foo(usize);
impl Drop for Foo {
    fn drop(&mut self) { println!("dropped"); }
}

#[thread_local]
static mut ATTR_TLS: Foo = Foo(0);

fn main() {
    let _ = std::thread::spawn(|| unsafe {
        println!("foo: {}", ATTR_TLS.0);
    })
    .join();
}
// Output:
// foo: 0
引用链接

[1] 原文链接: https://drmingdrmer.github.io/tips/#/page/rust-thread-local-drop [2] thread-local: https://en.wikipedia.org/wiki/Thread-local_storage [3] thread_local!{}: https://doc.rust-lang.org/std/macro.thread_local.html [4] #[thread_local]: https://doc.rust-lang.org/beta/unstable-book/language-features/thread-local.html [5] winter: https://github.com/zhang2014

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-12-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 分布式研究小院 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 引用链接
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档