Home About Contact

 

How to work with threads in Python

2 min read

Thread lets different parts of program run concurrently. Usually when you have a part of execution in your program that takes longer than usual to run, it’s better let it run in a thread without blocking the main program to handle the user’s interactions or other executions etc.

Thread in Python does not mean multi-processing, it still runs on a single processor. Functions run in different threads are simply taking turns to run.

import threading
import time
def my_func1():
   counter = 0 
   while counter < 100 :
      counter += 1
      print("counter is :"+str(counter))
      time.sleep(1)
   print("bye bye now")

def my_func2():
	txt = input() 
	while txt != 'x' :
		print("You've entered :" + txt +"\n")
		txt = input()
	print("bye, you've entered x")

In the above code, we have two functions my_func1 and my_func2.

Function my_func1 takes long time to execute, as it only exits when it's increased the counter to 100 and each time it'll take a one-second sleep; meaning you'll have to wait up to about 100 seconds then the following lines of instructions to be executed.

The function my_func2 keeps looping for the user's input at the command line and exits only when an "x" is entered.

thread1 = threading.Thread(target=my_func1)
thread1.start()

thread2 = threading.Thread(target=my_func2)
thread2.start()

In the above example we run the two functions in two separate threads, thus my_func1 and my_func2 will run concurrently, the output is as follows:

If my_func1 and my_func2 are not run in threads, then the program has to wait for my_func1 to finish first then only to run my_func2.

Spread the love
Posted on December 14, 2020 By Christopher Chee

Please leave us your comments below, if you find any errors or mistakes with this post. Or you have better idea to suggest for better result etc.


Our FB Twitter Our IG Copyright © 2024