SignaledTask.h

// SignaledTask.h
//
// Author David Barrett-Lennard
// (C)opyright Cedanet Pty Ltd 2013

#pragma once
#ifndef Ceda_cxMessage_SignaledTask_H
#define Ceda_cxMessage_SignaledTask_H

#include "cxMessage.h"
#include "AutoResetEvent.h"
#include "ThreadName.h"
#include <thread>
#include <functional>
#include <atomic>

#ifdef _MSC_VER
    // struct 'X' needs to have dll-interface to be used by clients of class 'Y'
    #pragma warning(disable:4251)
#endif

namespace ceda
{
class cxMessage_API SignaledTask
{
public:
    SignaledTask();
    ~SignaledTask();

    void Start(const char* threadName, std::function<void()> task);
    void Stop();
    void Signal();

    // A task can call this to poll whether it should complete as soon as possible
    bool Abort() const { return !started_; } 

private:
    xstring threadName_;
    std::thread thread_;
    volatile bool started_;

    // Event used to wake up the thread from its dormant state.  This can be for two reasons
    //    1.    The thread is being stopped
    //    2.    It is time to perform run the task
    AutoResetEvent wakeThreadEvent_;

    // Task to be executed when Signal() is called
    std::function<void()> task_;
};
} // namespace ceda
#endif // include guard