jeudi 25 juin 2015

Threaded base class C++

I want to do some threaded base class. I wrote the code, that I think should work, it compiles and runs but it doesn't display nothing. I think, the problem is in a callback, but I can be wrong. So, what is wrong in my code?

class ThreadedBase
{
public:
    ThreadedBase(bool start = false) : m_running(false) {
        if (start)
            this->start();
    }
    virtual ~ThreadedBase() {
        m_running = false;
        m_thread.join();
    }

    bool start(){
        if (m_running) {
            return false;
        };
        m_thread = std::thread(&ThreadedBase::run, this);
        m_running = true;
        return true;
    };

    bool stop(){
        if (!m_running) {
            return false;
        };
        m_running = false;
        return true;
    };

protected:
    virtual void threadedBlock() = 0;

    void run() {
        while (m_running) {
            threadedBlock();
        }
    }

private:
    std::thread m_thread;
    bool m_running;
};

class Test : public ThreadedBase
{
public:
    Test(bool start = true) : ThreadedBase(start) {}

    void threadedBlock() {
        std::cout << "Task\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
};

int main()
{
    Test t(true);
    t.start();

    std::this_thread::sleep_for(std::chrono::seconds(100));

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire