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')
	time.sleep(5)
	print('Function1 woke up from sleep')

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

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

Here is the output


python3.6 multithreading.py 
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

This site uses Akismet to reduce spam. Learn how your comment data is processed.