Multithreading in Python

aimtocode

Multithreading Definition

Multithreading is a process of executing multiple threads simulataneously..

A multithreaded program contains two or more parts that can run concurrently and each part can handle different task at the same time.

Multithreaded programs can run faster on computer systems with multiple CPUs, because theses threads can be executed truly concurrent.

A program can remain responsive to input. This is true both on single and on multiple CPU.

Threads of a process can share the memory of global variables. If a global variable is changed in one thread, this change is valid for all threads. A thread can have local variables.

Example:

In this example, we'll learn to start the thread in simplest way.



Output:

 thread function
 thread function
 thread function

Example 2:



Output:

 Thread 0 will sleep for 2 seconds. 
 Thread 3 will sleep for 2 seconds. 
 Thread 1 will sleep for 2 seconds. 
 Thread 2 will sleep for 2 seconds. 
 Thread 4 will sleep for 2 seconds. 
 Thread 5 will sleep for 2 seconds. 
 Thread 6 will sleep for 2 seconds. 

 Thread 7 will sleep for 2 seconds. 
 Thread 8 will sleep for 2 seconds. 
 Thread 9 will sleep for 2 seconds. 
 >>>

 Thread 0 is awake now.
 Thread 1 is awake now.
 Thread 5 is awake now.
 Thread 4 is awake now.
 Thread 2 is awake now.
 Thread 6 is awake now.
 Thread 3 is awake now.
 Thread 8 is awake now.
 Thread 7 is awake now.
 Thread 9 is awake now.

threading.Timer()

threading.Timer() function is used to create a new thread and it let you start as per given time by you,

Note: time must be specified in seconds only.

Example:


The Output will be printed after 5 seconds later.

Output:

 >>> Printed after 5 seconds!
aimtocode