Threads

What is a thread?

A thread is a sequence of instructions, executed one after the other. When a program is launched, its main function is executed as a thread. The execution of a program is called a process and the thread executing the main function is said to be its main thread. When the main thread stops, the process stops.

Processor core

Modern processors possess many cores. Each core is a unit that is able to execute instructions, independently from the other cores. That means that each core is a kind of sub-processor.

Logical vs physical thread

If a processor has 12 cores and is able to execute 12 threads simultaneously, then, the machine can execute 12 physical threads at the same time. A thread that is being executed on the processor is a physical thread. However, there can be, running at the same time on a computer, a number of threads way higher than the number of physical threads the processor can handle. If there are 64 active threads on a machine able to simultaneously execute 16 threads, then, there are 16 physical threads and 64 logical threads running.

Hyper-Threading

So, each core of a processor is able to execute a physical thread? Sometimes yes, but not always. Some processors are able to execute more than one thread per core (Usually 2). That means that, for example, some processors with 12 cores can actually execute 24 physical threads.

Parallel vs concurrent thread

Let us pretend there are 2 logical threads running on a computer. If each thread is running on one physical thread that is assigned to it, then they are said to be parallel threads. They are both executed at the same time.

However, if those 2 logical threads share a physical thread, then, they are said to be concurrent threads.

How can 2 logical threads share a single physical thread? By sharing its execution time. A way to do it would be to, for example, execute, alternatively, each thread for 1 milliseconds.

The threads are managed by the operating system, so it is the one that decides how the execution time of the physical threads is shared between the logical threads.

Multi-threaded programs

When a program is launched, its main function is executed as a logical thread. If it uses only 1 thread, the program is said to be single-threaded (This is the default). Since C++11, the C++ Standard Library provides tools to execute functions as logical threads. Earlier, to do so, we had to use external libraries or directly the library of the operating system.

Let us go to the next page to see how to make our programs multi-threaded, using the C++ Standard Library.