std :: thread未处理的异常访问此* [英] std::thread Unhanded exception accessing this*

查看:229
本文介绍了std :: thread未处理的异常访问此*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Timer类,调用传递给创建的函数,它循环和休眠的时间给定。
问题im是当尝试杀死该定时器从传递的函数我得到 pThis-> Stop()

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()

我似乎得到相同的崩溃即使我访问全局类对象

I seem to get the same crash even if i access the global class object

类:

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;
};

全球:

CTimer Timer;

主题:

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();
}

这样调用:

Timer.Start(2000, TimerThread, hwnd);


推荐答案

看看你是否可以在tick函数之外停止计时器。如果你不能,那么考虑让tick函数返回 bool ,以确定它是否应该继续。

See if you can stop the timer outside of the tick function. If you can't, then consider letting the tick function return a bool for whether it should keep going or not.

无论如何, 总是从不同的线程加入。

At any rate, the thread should always be joined, and always from a different thread.

这篇关于std :: thread未处理的异常访问此*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆