Introduce the WorkQueue
The WorkQueue allow other threads to submit tasks to be executed in the thread that the WorkQueue lives on. The WorkQueue will cancel all the pending tasks when it gets destructed, to make sure the tasks won't get called with invalid references.
This commit is contained in:
37
src/mbgl/util/work_queue.cpp
Normal file
37
src/mbgl/util/work_queue.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
#include <mbgl/util/work_queue.hpp>
|
||||
|
||||
#include <mbgl/util/run_loop.hpp>
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
WorkQueue::WorkQueue() : runLoop(RunLoop::Get()) {
|
||||
}
|
||||
|
||||
WorkQueue::~WorkQueue() {
|
||||
assert(runLoop == RunLoop::Get());
|
||||
|
||||
// Cancel all pending WorkRequests.
|
||||
while (!queue.empty()) {
|
||||
queue.pop();
|
||||
}
|
||||
}
|
||||
|
||||
void WorkQueue::push(std::function<void()>&& fn) {
|
||||
std::lock_guard<std::mutex> lock(queueMutex);
|
||||
|
||||
auto workRequest = runLoop->invokeCancellable(std::bind(&WorkQueue::pop, this, std::move(fn)));
|
||||
queue.push(std::move(workRequest));
|
||||
}
|
||||
|
||||
void WorkQueue::pop(const std::function<void()>& fn) {
|
||||
assert(runLoop == RunLoop::Get());
|
||||
|
||||
fn();
|
||||
|
||||
std::lock_guard<std::mutex> lock(queueMutex);
|
||||
queue.pop();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
36
src/mbgl/util/work_queue.hpp
Normal file
36
src/mbgl/util/work_queue.hpp
Normal file
@@ -0,0 +1,36 @@
|
||||
#ifndef MBGL_UTIL_WORK_QUEUE
|
||||
#define MBGL_UTIL_WORK_QUEUE
|
||||
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/work_request.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <queue>
|
||||
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
class RunLoop;
|
||||
|
||||
class WorkQueue : private util::noncopyable {
|
||||
public:
|
||||
WorkQueue();
|
||||
virtual ~WorkQueue();
|
||||
|
||||
void push(std::function<void()>&&);
|
||||
|
||||
private:
|
||||
void pop(const std::function<void()>&);
|
||||
|
||||
std::queue<std::unique_ptr<WorkRequest>> queue;
|
||||
std::mutex queueMutex;
|
||||
|
||||
RunLoop* runLoop;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user