|
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. When used properly, multithreading enables the programmer to simplify the application architecture by decoupling the user interface from the "real work." Note that this won't result in faster applications unless the computer has multiple processors, but the user interface will be more responsive. wxWidgets provides both a thread class and the necessary synchronization objects (mutexes and critical sections with conditions). The threading API in wxWidgets resembles the POSIX threading API (pthreads), although several functions have different names, and some features inspired by the Win32 thread API are also available. These classes make writing multithreaded applications easier, and they also provide some extra error checking compared with the native thread API. However, using threads is still a non-trivial undertaking, especially for large projects. Before starting a multithreaded application or adding multithreaded features to an existing one, it is worth considering alternatives to threads to implement the same functionality. In some situations, threads are the only reasonable choice, such as an FTP server application that launches a new thread for each new client. However, using an extra thread to show a progress dialog during a long computation would be overkill. In this case, you could do the calculations in an idle handler and call wxWindow::Update periodically to update the screen. For more details, see "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. |
|