Search code examples
c++boostmultithreadingwxwidgets

"Unhandled exception" error when mixing boost::thread with wxWidgets GUI


I was trying to access a wxDialog members from a boost::thread:

void AnotherThread(myWxDialog *dlg)
{
  wxMessageBox(dlg->TextBox1->GetValue(), "It works!"); // This throws an error
}

void myWxDialog::OnButtonClick(wxCommandEvent &event)
{
  boost::thread myThread(AnotherThread, this);
}

And I got this error:

Unhandled exception at 0x004043d7 in MyProgram.exe: 0xC0000005: Access violation reading location 0xbaadf00d.

I think this kind of action is not allowed between different thread.

So, is there any other way to do the same thing?

Any kind of help would be appreciated. :)

(Microsoft Visual C++ 2008 Express Edition)


Solution

  • 0xbaadf00d indicates that you're dereferencing an uninitialized pointer; if I were you I'd dig deeper with the debugger to see exactly where that pointer is (in dlg? in TextBox1? in what GetValue() returns? Somewhere else in wxMessageBox?). This would help you to understand where is the problem.

    Still, the biggest fault is trying to access GUI things from another thread: as explicitly stated here,

    When writing a multi-threaded application, it is strongly recommended that no secondary threads call GUI functions. The design which uses one GUI thread and several worker threads which communicate with the main one using events is much more robust and will undoubtedly save you countless problems (example: under Win32 a thread can only access GDI objects such as pens, brushes, device contexts created by itself and not by the other threads).

    There you can also find some suggestions about how to work around these limitations with events and other wxWidgets facilities.