wxThread

From WxWiki
Jump to navigation Jump to search
Official Classes SmallBlocks.png Archive Containers Controls Data Structures Database Date & Time Debug Device Contexts Dialogs Document & Views Drag & Drop Events Filesystem Frames Graphics Grid Cell Help HTML Logging Miscellaneous Networking Printing Sizers Streams Threading Windows

A thread is basically a path of execution through a program.

Threads are sometimes called light-weight processes, but the fundamental difference between threads and processes is that memory spaces of different processes are separated while all threads share the same address space.

While it makes it much easier to share common data between several threads, it also makes it much easier to shoot oneself in the foot, so careful use of synchronization objects such as mutexes (see wxMutex) or critical sections (see wxCriticalSection) is recommended. In addition, don't create global thread objects because they allocate memory in their constructor, which will cause problems for the memory checking system.

Prefer Entry() to the Constructor

If you have problems using something in the thread that you create in the constructor of the wxThread-derived class, move it to the Entry() function. That is much safer.

wxApp::Yield()

Many of the general applications of threads can also be implemented with wxApp::Yield(). This is, however, to be avoided, since in some cases this would cause an event loop to be recursively entered, which is a Bad Thing and hard to debug.

Problems Deleting a Thread

If you have

OnClose(...) {
  thread->Delete();
  Destroy();
}

Delete(), while waiting for the thread to destroy itself, processes messages. Since the window has not yet been destroyed while doing this, OnClose() is called *again* while waiting, which calls Delete() *again*. Once this recursive delete is complete, the first delete will hang, fail, or both. I worked around it by instead doing:

OnClose(...) {
  if (m_destroying) return;
  m_destroying++;                                                                                                                           
  thread->Delete();
  Destroy():
}

There is, however, some discussion about why OnClose() should be called again, and thus this shouldn't be needed.

General Tips When Debugging

Make sure that you specify wxTHREAD_JOINABLE when you need it. Not doing so will let the default constructor use wxTHREAD_DETACHED and result in mysterious access violations when deleting the thread which are likely to make you go mad.

See Also