我需要在一组任务之间分派作业。std::sync::deque足以解决此问题,但如果队列为空,则需要阻塞任务。
以下代码(在GitHub gist中可用)是如何使用std::sync::deque的实际示例
extern crate time;
use std::io::timer::sleep;
use std::sync::deque::{BufferPool, Empty, Abort, Data};
use std::time::Duration;
fn main() {
let start = time::precise_time_s();
let pool = BufferPool::new();
let (worker, stealer) = pool.deque();
for task_id in range(1i, 5) {
let sc = stealer.clone();
spawn(proc() {
loop {
let elapse = time::precise_time_s() - start;
match sc.steal() {
Empty => { println!("[{} @ {:#7.4}] No items", task_id, elapse); sleep(Duration::milliseconds(300)) },
Abort => println!("[{} @ {:#7.4}] ABORT. Retrying.", task_id, elapse),
Data(item) => println!("[{} @ {:#7.4}] Found {}", task_id, elapse, item)
}
}
});
}
for item in range(1i, 1000) {
for n in range(1i, 20) {
worker.push(item * n);
}
sleep(Duration::milliseconds(1000));
}
}我看到有一个std::sync::TaskPool,但是current implementation将作业发送给一个任务,即使线程忙于处理一个较旧的作业。
我的问题是:在队列中有任何项目之前,阻止任务的最佳方法是什么?
发布于 2014-09-20 20:42:25
可能的解决方案是使用信号量:
extern crate time;
use std::io::timer::sleep;
use std::sync::deque::{BufferPool, Empty, Abort, Data};
use std::sync::{Semaphore, Arc};
use std::time::Duration;
fn main() {
let start = time::precise_time_s();
let pool = BufferPool::new();
let (worker, stealer) = pool.deque();
let sem = Arc::new(Semaphore::new(0));
for task_id in range(1i, 5) {
let sc = stealer.clone();
let s = sem.clone();
spawn(proc() {
loop {
let elapse = time::precise_time_s() - start;
s.acquire();
match sc.steal() {
Empty => {
println!("[{} @ {:#7.4}] No items", task_id, elapse);
sleep(Duration::milliseconds(300))
},
Abort => {
println!("[{} @ {:#7.4}] ABORT. Retrying.", task_id, elapse);
s.release();
},
Data(item) => println!("[{} @ {:#7.4}] Found {}", task_id, elapse, item)
}
}
});
}
for item in range(1i, 1000) {
for n in range(1i, 20) {
worker.push(item * n);
sem.release();
}
sleep(Duration::milliseconds(1000));
}
}正如您在这里看到的,您将为每个生成的值释放一个信号量资源,并在从队列中获取值之前获取它。在这种情况下,返回值永远不会为空,但仍然可以中止,并且您必须释放资源,因为没有读取任何内容,但值仍在队列中。
另一种可能的解决方案是,当没有您想要的值时,使用阻塞的通道。为了提高性能,您必须对这两种解决方案进行基准测试。
https://stackoverflow.com/questions/25941576
复制相似问题