dimanche 28 février 2016

std::thread Unhanded exception accessing this*

I have a Timer class that calls a function passed to create and it loops and sleeps for what ever time given. Problem im having is when trying to kill that timer from withen the passed function i get that exception at pThis->Stop()

Class:

class CTimer
{
public:
    CTimer()
        :_running(false)
    {}

    ~CTimer() {
        if (_running.load(std::memory_order_acquire)) {
            Stop();
        };
    }

    void Stop()
    {
        _running.store(false, std::memory_order_release);
        if (_thread.joinable())
            _thread.join();
    }

    template <typename F, typename... A>
    void Start(int interval, F func, A&&... args)
    {
        if (_running.load(std::memory_order_acquire))
            Stop();

        _running.store(true, std::memory_order_release);
        _thread = std::thread([this, interval, func, &args...]()
        {
            while (_running.load(std::memory_order_acquire))
            {
                func(this, std::forward<A>(args)...);

                std::this_thread::sleep_for(std::chrono::milliseconds(interval));
            }
        });
    }

    bool Running() const noexcept {
        return (_running.load(std::memory_order_acquire) &&
            _thread.joinable());
    }

private:
    std::atomic<bool> _running;
    std::thread _thread;
};

Global:

CTimer Timer;

Thread:

void TimerThread(CTimer* pThis, HWND hwnd)
{
    // my code in side here
    // everything works fine till i try to stop within this thread


    // crash here
    pThis->Stop();
}

Call it like this:

Timer.Start(2000, TimerThread, hwnd);

Aucun commentaire:

Enregistrer un commentaire