diff options
Diffstat (limited to 'utils/MsgTask.cpp')
-rw-r--r-- | utils/MsgTask.cpp | 78 |
1 files changed, 46 insertions, 32 deletions
diff --git a/utils/MsgTask.cpp b/utils/MsgTask.cpp index 0a978ed..6ef689a 100644 --- a/utils/MsgTask.cpp +++ b/utils/MsgTask.cpp @@ -36,41 +36,33 @@ #include <loc_log.h> #include <loc_pla.h> -static void LocMsgDestroy(void* msg) { - delete (LocMsg*)msg; -} +namespace loc_util { -MsgTask::MsgTask(LocThread::tCreate tCreator, - const char* threadName, bool joinable) : - mQ(msg_q_init2()), mThread(new LocThread()) { - if (!mThread->start(tCreator, threadName, this, joinable)) { - delete mThread; - mThread = NULL; - } -} +class MTRunnable : public LocRunnable { + const void* mQ; +public: + inline MTRunnable(const void* q) : mQ(q) {} + virtual ~MTRunnable(); + // Overrides of LocRunnable methods + // This method will be repeated called until it returns false; or + // until thread is stopped. + virtual bool run() override; -MsgTask::MsgTask(const char* threadName, bool joinable) : - mQ(msg_q_init2()), mThread(new LocThread()) { - if (!mThread->start(threadName, this, joinable)) { - delete mThread; - mThread = NULL; - } -} + // The method to be run before thread loop (conditionally repeatedly) + // calls run() + virtual void prerun() override; -MsgTask::~MsgTask() { - msg_q_flush((void*)mQ); - msg_q_destroy((void**)&mQ); + // to interrupt the run() method and come out of that + virtual void interrupt() override; +}; + +static void LocMsgDestroy(void* msg) { + delete (LocMsg*)msg; } -void MsgTask::destroy() { - LocThread* thread = mThread; - msg_q_unblock((void*)mQ); - if (thread) { - mThread = NULL; - delete thread; - } else { - delete this; - } +MsgTask::MsgTask(const char* threadName) : + mQ(msg_q_init2()), mThread() { + mThread.start(threadName, std::make_shared<MTRunnable>(mQ)); } void MsgTask::sendMsg(const LocMsg* msg) const { @@ -82,12 +74,27 @@ void MsgTask::sendMsg(const LocMsg* msg) const { } } -void MsgTask::prerun() { +void MsgTask::sendMsg(const std::function<void()> runnable) const { + struct RunMsg : public LocMsg { + const std::function<void()> mRunnable; + public: + inline RunMsg(const std::function<void()> runnable) : mRunnable(runnable) {} + ~RunMsg() = default; + inline virtual void proc() const override { mRunnable(); } + }; + sendMsg(new RunMsg(runnable)); +} + +void MTRunnable::interrupt() { + msg_q_unblock((void*)mQ); +} + +void MTRunnable::prerun() { // make sure we do not run in background scheduling group set_sched_policy(gettid(), SP_FOREGROUND); } -bool MsgTask::run() { +bool MTRunnable::run() { LocMsg* msg; msq_q_err_type result = msg_q_rcv((void*)mQ, (void **)&msg); if (eMSG_Q_SUCCESS != result) { @@ -104,3 +111,10 @@ bool MsgTask::run() { return true; } + +MTRunnable::~MTRunnable() { + msg_q_flush((void*)mQ); + msg_q_destroy((void**)&mQ); +} + +} // namespace loc_util |