Jonathan Wood Jonathan Wood - 4 years ago 104
C++ Question

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
method, which is a

UINT COrganizerProgressDlg::RunBackgroundWorker(LPVOID pParam)
// Run organizer engine
COrganizerEngine engine(m_nNotifyMessage, (CWorkerData*)pParam);
catch (CException *e)
return 0;

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

The problem is that my
variable contains valid data before calling
, but seems to contain garbage within

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

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download