Multi threading in Python

Multi-threading is a way of achieving multitasking. Many times we run into a situation where do done need to run code sequentially and would like to run two processes (functions ) in parallel so save some time.

Typically python executes code sequentially. For example, if you have called a function, next sentence will be executed only after function in previous row has completed execution.

Here is the sample code for multi-threading. We will be using python moduleĀ threading

import threading
import time
from threading import Thread

def function1():
	print('Inside Function1. Now going to sleep')
	print('Function1 woke up from sleep')

def function2():
	print('Inside Function2. Now going to sleep')
	print('Function2 woke up from sleep')

if __name__ == '__main__':
    Thread(target = function1).start()
    Thread(target = function2).start()

Here is the output

Inside Function1. Now going to sleep
Inside Function2. Now going to sleep
Function2 woke up from sleep
Function1 woke up from sleep

As you can see function2 and function1 are running in parallel. You can see function2 woke up first from sleep


Leave a Reply

Your email address will not be published. Required fields are marked *