Threading

Threading — the ability of a processor to execute multiple threads concurrently.

# Python program to illustrate the concept 
# of threading 
# importing the threading module 
import threading 
  
def print_cube(num): 
    """ 
    function to print cube of given num 
    """
    print("Cube: {}".format(num * num * num)) 
  
def print_square(num): 
    """ 
    function to print square of given num 
    """
    print("Square: {}".format(num * num)) 
  
if __name__ == "__main__": 
    # creating thread 
    t1 = threading.Thread(target=print_square, args=(10,)) 
    t2 = threading.Thread(target=print_cube, args=(10,)) 
  
    # starting thread 1 
    t1.start() 
    # starting thread 2 
    t2.start() 
  
    # wait until thread 1 is completely executed 
    t1.join() 
    # wait until thread 2 is completely executed 
    t2.join() 
  
    # both threads completely executed 
    print("Done!") 

# Square: 100
# Cube: 1000
# Done!
  • allows you to have different parts of your program run concurrently and can simplify your design.
  • within a process share the same data space with the main thread and can therefore share information or communicate with each other more easily than if they were separate processes.
  • sometimes called light-weight processes and they do not require much memory overhead.
  • cheaper than processes.

Thread

Thread — a separate flow of execution.

Thread — is the smallest unit of processing that can be performed in an OS (Operating System).

Thread — a sequence of such instructions within a program that can be executed independently of other code.

an entity within a process that can be scheduled for execution.

Related concepts

Threading — Structure map

Clickable & Draggable!

Threading — Related pages: