Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing shared data from a worker thread

I have the following code:

void COrganizerProgressDlg::LaunchWorkerThread()
{
    CWorkerData data;
    data.m_pWndOrganizerProgressDlg = this;
    data.m_pWndImageOrganizerDlg = m_pWndImageOrganizerDlg;
    ::AfxBeginThread(RunBackgroundWorker, &data);
}

And here is my RunBackgroundWorker() method, which is a static method.

UINT COrganizerProgressDlg::RunBackgroundWorker(LPVOID pParam)
{
    try
    {
        // Run organizer engine
        COrganizerEngine engine(m_nNotifyMessage, (CWorkerData*)pParam);
        engine.Run();
    }
    catch (CException *e)
    {
        e->ReportError();
        e->Delete();
    }
    return 0;
}

The data is being used to initialize settings in my worker class.

The problem is that my data variable contains valid data before calling AfxBeginThread(), but seems to contain garbage within RunBackgroundWorker().

What am I missing? How can I access this data from my worker thread?

like image 662
Jonathan Wood Avatar asked Apr 02 '26 07:04

Jonathan Wood


1 Answers

data is an object with automatic storage duration. Once it goes out of scope, it is no longer valid. I'm assuming, that data goes out of scope before the worker thread gets a chance to pick up the information.

To solve this there are essentially 2 options:

  • Create a synchronization object (e.g. a CEvent), and have the worker thread signal it, when it is done reading the data. Call WaitForSingleObject in the main thread to block execution until that happens. This is subject to deadlocks, e.g. when the worker thread dies.
  • An easier solution is to use dynamic memory management. Use new to allocate a CWorkerData instance and pass the address to the worker thread. The worker thread can then call delete, whenever its done with the object.
like image 197
IInspectable Avatar answered Apr 03 '26 20:04

IInspectable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!