Doe*_*Doe 9 multithreading ffi rust
对于以下每个线程本地存储实现,如何使用编译器或标准库公开的标准ffi机制在Rust程序中访问外部线程局部变量?
Rust有一个夜间功能,允许链接到外部线程局部变量.此处跟踪功能的稳定性.
C11定义了_Thread_local用于定义对象的线程存储持续时间的关键字.还存在thread_local宏别名.
GCC还实现了一个用作关键字的Thread Local扩展__thread.
使用nightly(使用和gcc 5.4 测试)可以链接到外部C11 _Thread_local和gcc __thread变量rustc 1.17.0-nightly (0e7727795 2017-02-19)
#![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();
}
}
Run Code Online (Sandbox Code Playgroud)
这允许访问声明为以下任一项的变量:
_Thread_local extern int test_global;
extern __local int test_global;
Run Code Online (Sandbox Code Playgroud)
上面的Rust代码的输出将是:
1
1
1
1
1
Run Code Online (Sandbox Code Playgroud)
当变量被定义为线程局部时,这是预期的.