1
0
mirror of https://github.com/TomHarte/CLK.git synced 2024-11-29 12:50:28 +00:00

Adds DeferringAsyncTaskQueue as a base concurrency primitive.

This commit is contained in:
Thomas Harte 2017-12-15 22:14:09 -05:00
parent d66a33f249
commit eb6b612052
2 changed files with 48 additions and 0 deletions

View File

@ -79,3 +79,20 @@ void AsyncTaskQueue::flush() {
flush_condition->wait(lock); flush_condition->wait(lock);
#endif #endif
} }
void DeferringAsyncTaskQueue::defer(std::function<void(void)> function) {
if(!deferred_tasks_) {
deferred_tasks_.reset(new std::list<std::function<void(void)>>);
}
deferred_tasks_->push_back(function);
}
void DeferringAsyncTaskQueue::perform() {
std::shared_ptr<std::list<std::function<void(void)>>> deferred_tasks = deferred_tasks_;
deferred_tasks_.reset();
enqueue([deferred_tasks] {
for(auto &function : *deferred_tasks) {
function();
}
});
}

View File

@ -59,6 +59,37 @@ class AsyncTaskQueue {
#endif #endif
}; };
/*!
A deferring async task queue is one that accepts a list of functions to be performed but defers
any action until told to perform. It performs them by enquing a single asynchronous task that will
perform the deferred tasks in order.
It therefore offers similar semantics to an asynchronous task queue, but allows for management of
synchronisation costs, since neither defer nor perform make any effort to be thread safe.
*/
class DeferringAsyncTaskQueue: public AsyncTaskQueue {
public:
/*!
Adds a function to the deferral list.
This is not thread safe; it should be serialised with other calls to itself and to perform.
*/
void defer(std::function<void(void)> function);
/*!
Enqueues a function that will perform all currently deferred functions, in the
order that they were deferred.
This is not thread safe; it should be serialised with other calls to itself and to defer.
*/
void perform();
private:
// TODO: this is a shared_ptr because of the issues capturing moveables in C++11;
// switch to a unique_ptr if/when adapting to C++14
std::shared_ptr<std::list<std::function<void(void)>>> deferred_tasks_;
};
} }
#endif /* Concurrency_hpp */ #endif /* Concurrency_hpp */