When to Use Threads, and When Not To
A thread is basically a path of execution through a program. Threads are sometimes called lightweight processes, but the fundamental difference between threads and processes is that the memory spaces of different processes are separate, whereas all threads in the same process share the same address space. Although this makes it much easier to share common data between several threads, multithreading also makes it easier to shoot oneself in the proverbial foot by accessing the same data simultaneously, so careful use of synchronization objects such as mutexes and critical sections is recommended.Alternatives to Multithreading" toward the end of this chapter.If you decide to use threads in your application, it is strongly recommended that only the main thread call GUI functions. The wxWidgets thread sample shows that it is possible for many different threads to call GUI functions at once, but in general, it is a very poor design choice. A design that uses one GUI thread and several worker threads that communicate with the main one using events is much more robust and will undoubtedly save you countless problems. For example, under Win32, a thread can only access GDI objects such as pens, brushes, and so on, created by itself, not those created by other threads.For communication between threads, you can use wxEvtHandler::Add PendingEvent or its short version, wxPostEvent. These functions have thread-safe implementations so that they can be used for sending events between threads.