Threads and Multiprocessing
Simple applications tend to be very focused, concentrating on one task at a time. However, as your programs get more complex or sophisticated, you may want your application to start doing multiple things at once. Say you have any application that, among other things, periodically downloads information off a network and updates a window with the new information. For the best user experience, you would like the information retrieval to be independent of any other actions the application can take. Otherwise, the retrieval process will “lock up” your application for the duration, and your user will be left twiddling thumbs (or, more likely, cursing, as shown in Figure 14.4) until the download is complete. The best way to do this is to create a separate thread to handle the download.
Figure 14-4. Single-threaded versus multithreaded applications
Threads, which are sometimes called tasks, are independent execution paths within your application. They have their own stack and function almost like mini-applications. However, they share the same address space as the main application, which means they can share memory. This makes it easy to pass information between the thread and the main application. For example, if an application wants to spawn a thread to process an image in the background, it can simply pass a pointer to the image rather than copying the image ...
Get Learning Carbon now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.