Thread operations
In this section, we will learn how to create threads, pass arguments during their construction, return values from threads, cancel threads execution, catch exceptions, and much more.
Thread creation
When a thread is created, it executes immediately. It is only delayed by the OS scheduling process. If there are not enough resources to run both parent and child threads in parallel, the order in which they will run is not defined.
The constructor argument defines the function or function
object to be executed by the thread. This callable object should not return anything, as its return value will be ignored. If for some reason the thread execution ends with an exception, std::terminate
is called unless an exception is caught, as we will see later in this chapter.
In the following examples, we create six threads using different callable objects.
t1
using a function pointer:
void func() { std::cout << "Using function...