How to run a multi-thread in Python


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 or not. We do this check with the isAlive method of the threading class.  Your output should be similar to below when you run the code.

Background thread, doing loop number: 1
Write something here:
You wrote: ok
Write something here:
Background thread, doing loop number: 2
You wrote: ok2
Write something here:
Background thread, doing loop number: 3
Background thread, doing loop number: 4
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))
    print("Exiting background_thread")
background_thread = threading.Thread(target=background_thread, args=(5,) )
thread_finished = False

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

Featured Image: "A multithreaded process with two threads executing in time clearly showing that the threads execute separately and execute mutually exclusively in time." by Cburnett is licensed under CC BY-SA 3.0

Leave a Reply

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

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram