Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread-Safe Buffered Observable Priority Queue?

I'm writing a program where one thread needs to push items onto the queue, and one or more threads pops items off the queue and processes them. To avoid running out of memory, I'd like the producer thread to sleep when the queue gets full. Some items have a higher priority than others, so I'd like those to be processed first. If the items have the same priority, I'd like the one that was added first to be processed first.

I want to display the top 100 items or so in a WPF DataGrid, so it needs to be accessed by a UI thread as well. Would be nice if it could notify the UI thread that there's been an update as well, i.e., implements IObservable.

Is there a container class that will do all this?

For bonus points, I'm pretty sure the entire queue doesn't need to be locked both when enqueing and dequeing.

.NET 4 implementations are fine.

like image 585
mpen Avatar asked Sep 25 '10 04:09

mpen


People also ask

Is the PriorityQueue thread-safe?

PriorityQueue is essentially heapq implementation which is thread-safe.

Is Python PriorityQueue thread-safe?

Python queue PriorityQueue is thread-safe, but heapq doesn't guarantee thread safety.

What is PriorityQueue in python?

The priority queue is an advanced type of the queue data structure. Instead of dequeuing the oldest element, a priority queue sorts and dequeues elements based on their priorities. Priority queues are used to handle scheduling problems where some tasks are prioritized over others.


2 Answers

You are out of luck looking for a container - you have to implement one yourself. Be carefull with priorities - sorting gets slow fast. What I do is I have a queue class implemented myself that internally uses multiple arrays (one per priority - coded low, middle, high). This way I never sort. Avoid locks if you can (multi core assumed) and go for Spinlocks (.NET 4.0), they are faster / carry less overhead in a queue scenario.

like image 124
TomTom Avatar answered Sep 17 '22 23:09

TomTom


If you're on .NET 4 you should seriously consider the Task Parallel Library with a custom scheduler like the example QueuedTaskScheduler. I'm not sure it meets all your requirements, but it would be a good start.

like image 29
Sean Fausett Avatar answered Sep 18 '22 23:09

Sean Fausett