繁体   English   中英

如何在Rust中访问外部线程局部全局变量?

[英]How are foreign thread-local global variables accessed in Rust?

对于以下每个线程本地存储实现,如何使用编译器或标准库公开的标准ffi机制在Rust程序中访问外部线程局部变量?

  • C11
  • gcc的扩展名
  • 并行线程
  • Windows TLS API

Rust有一个夜间功能,允许链接到外部线程局部变量。 此处跟踪功能的稳定性。

C11 / GCC TLS扩展

C11定义了_Thread_local关键字来定义对象的线程存储持续时间 还存在thread_local宏别名。

GCC还实现了一个使用__thread作为关键字的Thread Local扩展。

每晚都可以使用外部C11 _Thread_local和gcc __thread变量进行rustc 1.17.0-nightly (0e7727795 2017-02-19) (使用rustc 1.17.0-nightly (0e7727795 2017-02-19)和gcc 5.4进行测试)

#![feature(thread_local)]

extern crate libc;

use libc::c_int;

#[link(name="test", kind="static")]
extern {
    #[thread_local]
    static mut test_global: c_int;
}

fn main() {
    let mut threads = vec![];
    for _ in 0..5 {
        let thread = std::thread::spawn(|| {
            unsafe {
                test_global += 1;
                println!("{}", test_global);
                test_global += 1;
            }
        });
        threads.push(thread);
    }

    for thread in threads {
        thread.join().unwrap();
    }
}

这允许访问声明为以下任一项的变量:

_Thread_local extern int test_global;
extern __local int test_global;

上面的Rust代码的输出将是:

1
1
1
1
1

当变量被定义为线程局部时,这是预期的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM