thread::spawn() 不同,这个新特性允许线程借用局部变量,而不仅仅是静态变量。借用官方例子:use std::thread;let mut a = vec![1, 2, 3];let mut x = 0;
thread::scope(|s| {
s.spawn(|| { println!("hello from the first scoped thread"); // borrow `a` here
dbg!(&a);
});
s.spawn(|| { println!("hello from the second scoped thread"); // mutably borrow `x`, because no other threads are using it
x += a[0] + a[2];
}); println!("hello from the main thread");
});// after the scope, can modify and access the variables againa.push(4);assert_eq!(x, a.len());
Mutex::new,RwLock::new 和 Condvar::new 都是 const function。这意味着现在可以将这些类型用作静态变量,而不再需要 lazy_static 或 once_cell 或其他解决方法。
主页:https://readyset.io/
type Person = name: string, job: ref string// Infer that the data referenced via `&` should not be freed inside this functionmake_person name =
Person name &"programmer"// bob is only used at this scope, so it can be safely freed afterwardbob = make_person "bob"// unlike ownership systems, aliasing is allowed with lifetime inferencebob_twin = bob
assert (bob.name == bob_twin.name)
use std::{thread, time::Duration};struct MyTask;impl quartz_sched::Job for Box<MyTask> { fn execute(&self) { println!("[+] Executing 'MyTask'");
} fn description(&self) -> String { "my task".to_string()
} fn key(&self) -> i64 { 43
}
}fn main() { let mut sched: quartz_sched::Scheduler = quartz_sched::Scheduler::new(); // start the scheduler
// spawns execution and feeder threads
sched.start(); // execute after duration N
sched.schedule_task(quartz_sched::schedule_task_after(
Duration::from_secs(1), Box::new(MyTask),
)); // get scheduled job meta info from scheduler
match sched.get_scheduled_job(/*key*/ 43) { Some(job) => { println!("[+] Next run at tick: {}", &job.next_runtime);
} None => {}
};
thread::sleep(Duration::from_secs(20)); // scheduler will stop after getting dropped
// alternatively, call sched.stop() to stop
// the scheduler.
// delete task associated with key from scheduler
_ = sched.delete_task(43);
}
From 日报小组 长琴
原文作者:Rust语言中文社区;如有侵权,请联系管理员删除。