私はtime.sleep
平野、スレッドを使用するタイマーのためではない探しています:RustにはPythonのスレッディングと同等の機能がありますか?
from threading import Timer
def x():
print "hello"
t = Timer(2.0, x)
t.start()
t = Timer(2.0, x)
t.start()
私はtime.sleep
平野、スレッドを使用するタイマーのためではない探しています:RustにはPythonのスレッディングと同等の機能がありますか?
from threading import Timer
def x():
print "hello"
t = Timer(2.0, x)
t.start()
t = Timer(2.0, x)
t.start()
あなたはそれが唯一のツールを使用して、類似したバージョンを自分で書くのは簡単ですtimerクレート
extern crate timer;
extern crate chrono;
use timer::Timer;
use chrono::Duration;
use std::thread;
fn x() {
println!("hello");
}
fn main() {
let timer = Timer::new();
let guard = timer.schedule_repeating(Duration::seconds(2), x);
// give some time so we can see hello printed
// you can execute any code here
thread::sleep(::std::time::Duration::new(10, 0));
// stop repeating
drop(guard);
}
を使用することができます
use std::thread;
use std::time::Duration;
struct Timer<F> {
delay: Duration,
action: F,
}
impl<F> Timer<F>
where
F: FnOnce() + Send + Sync + 'static,
{
fn new(delay: Duration, action: F) -> Self {
Timer { delay, action }
}
fn start(self) {
thread::spawn(move || {
thread::sleep(self.delay);
(self.action)();
});
}
}
fn main() {
fn x() {
println!("hello");
let t = Timer::new(Duration::from_secs(2), x);
t.start();
}
let t = Timer::new(Duration::from_secs(2), x);
t.start();
// Wait for output
thread::sleep(Duration::from_secs(10));
}
pointed out by malbarboとすると、これで新しいスレ各タイマーの広告。これはスレッドを再利用するソリューションよりも高価になる可能性がありますが、これは非常に簡単な例です。
新しいスレッドを割り当てるには非効率的であることに注意してください。それぞれの 'start'呼び出しです。 – malbarbo
@malbarbo素晴らしい点!繰り返しタスクが必要な場合は、同じスレッドを何度も何度も繰り返し使用する方がよいでしょう。私はPythonのセマンティクスにマッチさせようとしていました。 – Shepmaster
これを使用して可変構造体のフィールドを更新できますか? – lsund
@lsund他の場所からアクセス可能なクロージャーに可変参照を残すことができるかどうかを判断するには、クレートのソースから、その答えが 'Mutex''や 'Arc'dなどを除いて' no ' 'セルと友人のグローバル(または'安全でない 'コード)への参照。 – user
([チャンネル](https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html)と[scoped_tls](https://github.com/alexcrichton/scoped )、そして、最後にあなたは 'Send'-wayの方法でオブジェクトを包む必要があります) – user