以下是每种线程本地存储实现方式,使用标准ffi机制和编译器或标准库提供的方法,如何在Rust程序中访问外部线程本地变量?
- C11
- gcc的tls扩展
- pthreads
- Windows TLS API
_Thread_local
关键字来定义对象的线程存储期。还存在thread_local宏别名。__thread
作为关键字。
使用nightly版本(已测试rustc 1.17.0-nightly (0e7727795 2017-02-19)
和gcc 5.4),可以链接到外部C11 _Thread_local
和gcc __thread
变量。
#![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;
1
1
1
1
1
pub
,则应该能够从任何地方访问它。请参见LocalKey
和thread_local
,或者查看playground。 - rnstlr