tags:

views:

92

answers:

3

I'm writing a thread-pool for Qt as QRunnable doesn't handle event loops in new threads.

Not too familiar with STL, what would be the best way to pop() something by priority? Priority should probably be a property of MyRunnable imo, but I can always give that info to an STL container when adding the runnable to the queue.

+3  A: 

The standard library has std::priority_queue, which is, as its name suggests, a generic priority queue implementation.

James McNellis
+1. I don't know why my answer has more upvotes than yours :( They seem to say the same thing.
Billy ONeal
+4  A: 

By pop() I'm assuming you want some sort of a stack structure. I'm unsure how to achieve that with stack semantics, but the priority issues could be solved simply with std::priority_queue.

Billy ONeal
+2  A: 

Not familiar with QT, but as other suggest, use a priority_queue.

You'll also need a functor to allow the structure to access the priority information and specify the sorting order.

struct is_higher_priority {
    bool operator()( MyRunnable const &l, MyRunnable const &b )
        { return l.priority > r.priority; }
};

std::priority_queue< MyRunnable, std::deque<MyRunnable>, is_higher_priority > q;

...

q.push( task_1 );
q.push( task_2 );
q.push( task_3 );

MyRunnable &highest = q.top();
highest.run();
q.pop();
Potatoswatter
But don't use non-atomic `top`/`pop` combination in a multithreaded program.
Ben Voigt
Yes, it's good to lock shared structures…
Potatoswatter