Thread<T> is a generic thread management object that starts a thread, creates an object T in that thread and calls its .start() function. When the Thread<T> object is destructed (which must happen in the thread that created it), it'll call the object's .stop() function, and wait for thread termination. The .stop() function must somehow get the thread to terminate. Note that object T's constructor/destructor/start()/stop() must be protected/private, and Thread<T> must be declared as a friend class. All public functions may be called from any thread and are exposed through operator->(). RunLoop encapsulates a libuv runloop and has a facility of dispatching function objects to the thread. It can be used either as a worker thread class by itself, or it can be derived from. This commit converts SQLiteCache to derive from RunLoop and removes the custom code used previously for managing the cache thread.
52 lines
1.0 KiB
C++
52 lines
1.0 KiB
C++
#ifndef MBGL_UTIL_RUN_LOOP
|
|
#define MBGL_UTIL_RUN_LOOP
|
|
|
|
#include <mutex>
|
|
#include <functional>
|
|
#include <queue>
|
|
|
|
namespace uv {
|
|
class async;
|
|
class loop;
|
|
}
|
|
|
|
namespace mbgl {
|
|
namespace util {
|
|
|
|
template <typename T> class Thread;
|
|
|
|
class RunLoop {
|
|
friend Thread<RunLoop>;
|
|
|
|
protected:
|
|
// These are called by the Thread<> wrapper.
|
|
RunLoop();
|
|
~RunLoop();
|
|
|
|
// Called by the Thread<> wrapper to start the loop. When you implement this
|
|
// method in a child class, you *must* call this function as the last action.
|
|
void start();
|
|
|
|
protected:
|
|
// Called by the Thread<> wrapper to terminate this loop.
|
|
void stop();
|
|
|
|
private:
|
|
// Invokes function in the run loop.
|
|
void process();
|
|
|
|
public:
|
|
// Schedules a function to be executed as part of this run loop.
|
|
void invoke(std::function<void()> fn);
|
|
|
|
private:
|
|
const std::unique_ptr<uv::loop> runloop;
|
|
const std::unique_ptr<uv::async> runloopAsync;
|
|
std::mutex runloopMutex;
|
|
std::queue<std::function<void()>> runloopQueue;
|
|
};
|
|
|
|
}
|
|
}
|
|
|
|
#endif |