Finish thread by atomic bool crash

0

I have following worker thread:

class CWorkerThread
{
public:
    CWorkerThread(){}
    ~CWorkerThread(){}

    bool startUiThread()
    {
        try
        {
            std::thread th(&CRefreshUiWorkerThread::operator(), this);
            if (th.joinable())
            {
                th.detach();
            }
        }
        catch (std::exception ex)
        {
            //print logs
            return false;
        }

        //print logs
        return true;
    }

    void stopUiThread()
    {
        m_bFinishFlag = true;
    }

protected:
    void operator()()
    {
        while (!refFinishFlag)
        {
            //Do some stuff here

            //Sleep thread
            std::this_thread::sleep_for(std::chrono::seconds(6));
        }
    }

private:
    std::atomic<bool> m_bFinishFlag = false;
};

This is a part of MFC dll. During finishing dll I would like to terminate this thread by using atomic bool flag. So inside MFC's ExitInstance, method stopUiThread is called. But I'm getting following error:

First-chance exception at 0x08789E64 (mydll.dll) in MyApp.exe: 0xC0000005: Access violation writing location 0x00000030.

This is the call stack where the error occurs:

>   mydll.dll!std::_Store_seq_cst_1(volatile unsigned char * _Tgt, unsigned char _Value) Line 343   C++
    mydll.dll!std::_Atomic_store_1(volatile unsigned char * _Tgt, unsigned char _Value, std::memory_order _Order) Line 361  C++
    mydll.dll!std::atomic_store_explicit(std::atomic_bool * _Atom, bool _Value, std::memory_order _Order) Line 546  C++
    mydll.dll!std::atomic_store(std::atomic_bool * _Atom, bool _Value) Line 558 C++
    mydll.dll!std::atomic_bool::operator=(bool _Value) Line 756 C++
    mydll.dll!std::atomic<bool>::operator=(bool _Val) Line 204  C++
    mydll.dll!CWorkerThread::stopUiThread() Line 87 C++
    mydll.dll!CMyDll::ExitInstance() Line 97    C++

Does anyone explain me where this error comes from and how to fix it?

c++
multithreading
atomic
asked on Stack Overflow Sep 15, 2018 by drewpol

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0