如何将对堆栈变量的引用传递给线程?
LoggerLoggerLogger
Wrapperrun_thread
use std::fmt::Debug;use std::thread;struct Wrapper<T: Debug> {
val: T,}fn run_thread<T: Debug>(wrapper: Wrapper<T>) {
let thr = thread::spawn(move || {
println!("{:?}", wrapper.val);
});
thr.join();}fn main() {
run_thread(Wrapper::<i32> { val: -1 });}wrapperrun_thread
use std::fmt::Debug;use std::thread;struct Wrapper<T: Debug + Send> {
val: T,}fn run_thread<T: Debug + Send + 'static>(wrapper: Wrapper<T>) {
let thr = thread::spawn(move || {
println!("{:?}", wrapper.val);
});
thr.join();}fn main() {
run_thread(Wrapper::<i32> { val: -1 });}T
use std::fmt::Debug;use std::thread;struct Wrapper<T: Debug + Send> {
val: T,}fn run_thread<T: Debug + Send + 'static>(wrapper: Wrapper<T>) {
let thr = thread::spawn(move || {
println!("{:?}", wrapper.val);
});
thr.join();}fn main() {
let mut v = Vec::new();
for i in 0..1000 {
v.push(i);
}
run_thread(Wrapper { val: &v });}error: `v` does not live long enough
--> src/main.rs:22:32
|
22 | run_thread(Wrapper { val: &v });
| ^ does not live long enough
23 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...LoggerArcArc
隔江千里
慕森王
相关分类