Threads
Introduction
Normally when we run a program we have an instruction that is executed followed by another instruction and so on. This is called a path of execution. With threading we can have more than one path of execution at the same time. How does this work with a single CPU ? The same way a single CPU can run multiple processes by switching among processes. Here the CPU will switch among the threads in a process. However we don't know how much time the CPU will allocate to each thread. That is not determinstic. This comes from the definition of thread. Also if there are multiple CPU's in a system then the operating system may have the threads run on different CPU's and that will speed up the program.C++ did not have support for threads before C++ and the programmer had to rely on the underlying system. Unix programmers used Unix functions and Windows programmer used the Microsoft SDK API as an example. C++ 11 provides classes and constructs for threads in a uniform manner. A C++ program using the C++ 11 is more portable than pre C++ 11.
Let's say we have a server program processing requests that come in a sequential manner. We have one request coming in after another. If a request comes in and takes 1 hour to process then the requests after that have to wait for 1 hour. However with threads we can create a thread for each request and the requests that come in after the 1 hour request can be processed at the same time giving an overall better response time. If we have a server like program it is most likely using threads.
We have a GUI application that has a print dialog box that is printing 100 pages. The print function inside the program is sending the data to the printer but at the same time we want the user to be able to click the "Cancel" button on the dialog box. We can place the "print" function in it's own thread. If we have a GUI program it is most likely using threads.