Skip to content

Commit c9072ef

Browse files
committed
fix: using priority and sequential queues instead; fixes issue #1
1 parent 1558746 commit c9072ef

1 file changed

Lines changed: 59 additions & 3 deletions

File tree

src/main.cpp

Lines changed: 59 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <clocale>
55
#include <filesystem>
66
#include <iostream>
7+
#include <map>
78
#include <queue>
89
#include <vector>
910
namespace fs = std::filesystem;
@@ -274,6 +275,15 @@ class Task
274275
ncnn::Mat outimage;
275276
};
276277

278+
// comparator for priority queue (lower id has higher priority)
279+
struct TaskComparator
280+
{
281+
bool operator()(const Task& a, const Task& b)
282+
{
283+
return a.id > b.id; // cigher id has lower priority
284+
}
285+
};
286+
277287
class TaskQueue
278288
{
279289
public:
@@ -304,7 +314,7 @@ class TaskQueue
304314
condition.wait(lock);
305315
}
306316

307-
v = tasks.front();
317+
v = tasks.top();
308318
tasks.pop();
309319

310320
lock.unlock();
@@ -315,11 +325,57 @@ class TaskQueue
315325
private:
316326
ncnn::Mutex lock;
317327
ncnn::ConditionVariable condition;
318-
std::queue<Task> tasks;
328+
std::priority_queue<Task, std::vector<Task>, TaskComparator> tasks;
329+
};
330+
331+
class SequentialTaskQueue
332+
{
333+
public:
334+
SequentialTaskQueue() : next_id(1) {}
335+
336+
void put(const Task& v)
337+
{
338+
lock.lock();
339+
340+
while (tasks.size() >= 8) // FIXME hardcode queue length
341+
{
342+
condition.wait(lock);
343+
}
344+
345+
tasks[v.id] = v;
346+
347+
lock.unlock();
348+
349+
condition.signal();
350+
}
351+
352+
void get(Task& v)
353+
{
354+
lock.lock();
355+
356+
while (tasks.find(next_id) == tasks.end())
357+
{
358+
condition.wait(lock);
359+
}
360+
361+
v = tasks[next_id];
362+
tasks.erase(next_id);
363+
next_id++;
364+
365+
lock.unlock();
366+
367+
condition.signal();
368+
}
369+
370+
private:
371+
ncnn::Mutex lock;
372+
ncnn::ConditionVariable condition;
373+
std::map<int, Task> tasks;
374+
int next_id;
319375
};
320376

321377
TaskQueue toproc;
322-
TaskQueue tosave;
378+
SequentialTaskQueue tosave;
323379

324380
static int read_bytes(unsigned char* buf, size_t n)
325381
{

0 commit comments

Comments
 (0)