1111
1212#include " Framework/AsyncQueue.h"
1313#include " Framework/Signpost.h"
14+ #include " x9.h"
1415#include < numeric>
1516
1617O2_DECLARE_DYNAMIC_LOG (async_queue);
1718
1819namespace o2 ::framework
1920{
2021AsyncQueue::AsyncQueue ()
22+ : inbox(x9_create_inbox(16 , " async_queue" , sizeof (AsyncTask)))
2123{
24+ this ->inbox = x9_create_inbox (16 , " async_queue" , sizeof (AsyncTask));
2225}
2326
2427auto AsyncQueueHelpers::create (AsyncQueue& queue, AsyncTaskSpec spec) -> AsyncTaskId
@@ -31,11 +34,39 @@ auto AsyncQueueHelpers::create(AsyncQueue& queue, AsyncTaskSpec spec) -> AsyncTa
3134
3235auto AsyncQueueHelpers::post (AsyncQueue& queue, AsyncTask const & task) -> void
3336{
34- queue.tasks .push_back (task);
37+ // Until we do not manage to write to the inbox, keep removing
38+ // items from the queue if you are the first one which fails to
39+ // write.
40+ while (!x9_write_to_inbox (queue.inbox , sizeof (AsyncTask), &task)) {
41+ AsyncQueueHelpers::flushPending (queue);
42+ }
43+ }
44+
45+ auto AsyncQueueHelpers::flushPending (AsyncQueue& queue) -> void
46+ {
47+ bool isFirst = true ;
48+ if (!std::atomic_compare_exchange_strong (&queue.first , &isFirst, false )) {
49+ // Not the first, try again.
50+ return ;
51+ }
52+ // First thread which does not manage to write to the queue.
53+ // Flush it a bit before we try again.
54+ AsyncTask toFlush;
55+ // This potentially stalls if the inserting tasks are faster to insert
56+ // than we are to retrieve. We should probably have a cut-off
57+ while (x9_read_from_inbox (queue.inbox , sizeof (AsyncTask), &toFlush)) {
58+ queue.tasks .push_back (toFlush);
59+ }
60+ queue.first = true ;
3561}
3662
3763auto AsyncQueueHelpers::run (AsyncQueue& queue, TimesliceId oldestPossible) -> void
3864{
65+ // We synchronize right before we run to get as many
66+ // tasks as possible. Notice we might still miss some
67+ // which will have to handled on a subsequent iteration.
68+ AsyncQueueHelpers::flushPending (queue);
69+
3970 if (queue.tasks .empty ()) {
4071 return ;
4172 }
0 commit comments