What is a thread?

A thread is an independent execution flow that can be executed in parallel and concurrently with other threads in the system.

Multiple threads can share data and resources, taking advantage of the so-called space of shared information. The specific implementation of threads and processes depends on the OS on which you plan to run the application, but, in general, it can be stated that a thread is contained inside a process and that different threads in the same process conditions share some resources. In contrast to this, different processes do not share their own resources with other processes.

A thread is composed of three elements: program counters, registers, and stack. Shared resources with other threads of the same process essentially include data and OS resources. Moreover, threads have their own state of execution, namely, thread state, and can be synchronized with other threads.

A thread state can be ready, running, or blocked:

  • When a thread is created, it enters the Ready state.
  • A thread is scheduled for execution by the OS (or by the runtime support system) and, when its turn arrives, it begins execution by going into the Running state.
  • The thread can wait for a condition to occur, passing from the Running state to the Blocked state. Once the locked condition is terminated, the Blocked thread returns to the Ready state:

Thread life cycle

The main advantage of multithreading programming lies in performances, as the context switch between processes turns out to be much heavier than the switch context between threads that belong to the same process.

In the next recipes, until the end of the chapter, we will examine the Python threading module, introducing its main functions through programming examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset