将两种算法的性能同步到最慢的瓶颈
Synchronizing the performance of two algorithms to that of the slowest bottleneck
我有两种方法。一种方法检索某些数据,另一种方法处理该数据。
两种算法都以不同的速度运行,所以我想同步两种算法的性能,以便它们 运行 处于瓶颈速度。我正在考虑使用最大大小的消息队列。在队列达到其最大大小之前,检索方法会继续填充列表,而只要列表中有项目,处理方法就会在不同的线程上从列表中删除项目。如果列表达到其最大大小,那么它将等待,直到队列不再达到其最大大小。
这听起来是不是最合乎逻辑的方法?
我正在考虑某种形式的通用 class 类似于
Queue<T> _theQueue;
private int _maxQueueSize;
Func<T> _processor;
Func<T> _populator;
ChasedQueue(Func<T> processor, Funct<T> populator, int maxQueueSize = 30)
{
_theQueue = new Queue<T>();
_maxQueueSize =
_processor = processor;
_populator = populator;
}
public void Start()
{
new Thread(() => StartChaser()).Start();
new Thread(() => StartPopulator()).Start();
}
private void StartChaser()
{
while ((element = _documentQueue.poll) != null)
{
_processor(_documentQueue.Dequeue());
}
}
private void StartPopulator()
{
foreach(var item in _populator)
{
while(_theQueue.Count < _maxQueueSize)
{
_documentQueue.Enqueue(item);
}
}
}
为了完整起见,将我的评论提升为成熟的答案:
ReactiveExtensions,即Zip, seems like a good fit [example here] 。您的两个算法只会将它们的流式传输结果公开为您可以压缩的可观察对象...
我有两种方法。一种方法检索某些数据,另一种方法处理该数据。 两种算法都以不同的速度运行,所以我想同步两种算法的性能,以便它们 运行 处于瓶颈速度。我正在考虑使用最大大小的消息队列。在队列达到其最大大小之前,检索方法会继续填充列表,而只要列表中有项目,处理方法就会在不同的线程上从列表中删除项目。如果列表达到其最大大小,那么它将等待,直到队列不再达到其最大大小。
这听起来是不是最合乎逻辑的方法?
我正在考虑某种形式的通用 class 类似于
Queue<T> _theQueue;
private int _maxQueueSize;
Func<T> _processor;
Func<T> _populator;
ChasedQueue(Func<T> processor, Funct<T> populator, int maxQueueSize = 30)
{
_theQueue = new Queue<T>();
_maxQueueSize =
_processor = processor;
_populator = populator;
}
public void Start()
{
new Thread(() => StartChaser()).Start();
new Thread(() => StartPopulator()).Start();
}
private void StartChaser()
{
while ((element = _documentQueue.poll) != null)
{
_processor(_documentQueue.Dequeue());
}
}
private void StartPopulator()
{
foreach(var item in _populator)
{
while(_theQueue.Count < _maxQueueSize)
{
_documentQueue.Enqueue(item);
}
}
}
为了完整起见,将我的评论提升为成熟的答案:
ReactiveExtensions,即Zip, seems like a good fit [example here] 。您的两个算法只会将它们的流式传输结果公开为您可以压缩的可观察对象...