Skip to content

How to run a multi-thread in Python

Introduction

How to run a multi-thread in Python - While coding, we sometimes want the program to do multiple things at once. You may have a script where you run a background function, checking for changes as you go along. It can also be as simple as disabling an Entry to not allow the user to input more text for a while. In this post, we will look at a simple way of how to use multiple threads in Python.

Let us start with a thread running in the background. First, we define our background function background_thread. We give it the loops argument to know how many times it should execute. We then use the time.sleep method to wait for two seconds before continuing the loop. We start the thread and then enter our target as the background_thread function, with the arguments 5. Note that you have to put your argument enclosed in parentheses and with a comma after it. In case that you omit the comma, you will get the following error message: TypeError: background_thread() argument after * must be an iterable, not int.

Start the thread with the start method. Note that we are using a boolean thread_finished to check whether the background thread is done. We do this check with the isAlive method of the threading class.  Your output should be like below when you run the code.

Background thread, doing loop number: 1
Write something here:
ok
You wrote: ok
Write something here:
Background thread, doing loop number: 2
ok2
You wrote: ok2
Write something here:
Background thread, doing loop number: 3
Background thread, doing loop number: 4
ok3
You wrote: ok3
Write something here:
Background thread, doing loop number: 5
Exiting background_thread
I am done
You wrote: I am done

#! python3

import threading

import time

def background_thread(loops):
for i in range(loops):
print("Background thread, doing loop number: {}".format(i+1))
time.sleep(2)
print("Exiting background_thread")

background_thread = threading.Thread(target=background_thread, args=(5,) )
background_thread.start()
thread_finished = False

while not thread_finished:
if not background_thread.isAlive():
thread_finished = True
else:
my_input = input("Write something here:\n")
print("You wrote: {}".format(my_input))