[core] Abstract main loop inside RunLoop class
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
#ifndef MBGL_UTIL_RUN_LOOP
|
||||
#define MBGL_UTIL_RUN_LOOP
|
||||
|
||||
#include <mbgl/util/async_task.hpp>
|
||||
#include <mbgl/util/noncopyable.hpp>
|
||||
#include <mbgl/util/work_task.hpp>
|
||||
#include <mbgl/util/work_request.hpp>
|
||||
@@ -15,19 +16,26 @@
|
||||
namespace mbgl {
|
||||
namespace util {
|
||||
|
||||
typedef void * LOOP_HANDLE;
|
||||
|
||||
class RunLoop : private util::noncopyable {
|
||||
public:
|
||||
RunLoop(uv_loop_t*);
|
||||
enum class Type : uint8_t {
|
||||
Default,
|
||||
New,
|
||||
};
|
||||
|
||||
RunLoop(Type type = Type::Default);
|
||||
~RunLoop();
|
||||
|
||||
static RunLoop* Get() {
|
||||
return current.get();
|
||||
}
|
||||
|
||||
static uv_loop_t* getLoop() {
|
||||
return current.get()->get();
|
||||
}
|
||||
static LOOP_HANDLE getLoopHandle();
|
||||
|
||||
void run();
|
||||
void runOnce();
|
||||
void stop();
|
||||
|
||||
// Invoke fn(args...) on this RunLoop.
|
||||
@@ -39,7 +47,7 @@ public:
|
||||
std::move(tuple));
|
||||
|
||||
withMutex([&] { queue.push(task); });
|
||||
async.send();
|
||||
async->send();
|
||||
}
|
||||
|
||||
// Post the cancellable work fn(args...) to this RunLoop.
|
||||
@@ -56,7 +64,7 @@ public:
|
||||
flag);
|
||||
|
||||
withMutex([&] { queue.push(task); });
|
||||
async.send();
|
||||
async->send();
|
||||
|
||||
return std::make_unique<WorkRequest>(task);
|
||||
}
|
||||
@@ -90,13 +98,11 @@ public:
|
||||
flag);
|
||||
|
||||
withMutex([&] { queue.push(task); });
|
||||
async.send();
|
||||
async->send();
|
||||
|
||||
return std::make_unique<WorkRequest>(task);
|
||||
}
|
||||
|
||||
uv_loop_t* get() { return async.get()->loop; }
|
||||
|
||||
private:
|
||||
template <class F, class P>
|
||||
class Invoker : public WorkTask {
|
||||
@@ -143,12 +149,27 @@ private:
|
||||
|
||||
using Queue = std::queue<std::shared_ptr<WorkTask>>;
|
||||
|
||||
void withMutex(std::function<void()>&&);
|
||||
void process();
|
||||
void withMutex(std::function<void()>&& fn) {
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
fn();
|
||||
}
|
||||
|
||||
void process() {
|
||||
Queue queue_;
|
||||
withMutex([&] { queue_.swap(queue); });
|
||||
|
||||
while (!queue_.empty()) {
|
||||
(*(queue_.front()))();
|
||||
queue_.pop();
|
||||
}
|
||||
}
|
||||
|
||||
Queue queue;
|
||||
std::mutex mutex;
|
||||
uv::async async;
|
||||
std::unique_ptr<AsyncTask> async;
|
||||
|
||||
class Impl;
|
||||
std::unique_ptr<Impl> impl;
|
||||
|
||||
static uv::tls<RunLoop> current;
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user