How to run a Function in a new Thread in Python

In this Python tutorial we will explore how to execute a function in a new thread.

If you have a program where many functions are being called, or the main thread is busy with an I/O operation then it’s a good idea to create a new thread to handle some of the work. This can improve performance and allow you to have multiple tasks running in parallel.


Execute Function in new Thread

Let’s explore step by step how to execute a function in a new thread in Python.

1# First we need to import the Thread() Class from the threading library

from threading import Thread

2# Next we need the create the Thread object. Shown below is the syntax.

thread = Thread(target = function, args = (arg1, ))

The target parameter takes a function name, and the args parameter takes a tuple of values. Don’t forget to add a comma after the last argument in the tuple. If the target function takes no parameters, no need to include the args parameter.

3# Now we need to call the start() method on the thread so it begins executing the target function.

thread.start()

4# We need to make the main thread wait for the child thread until the child thread is finished, by using the join() method.

thread.join()

We typically add this at the very end of the program, to prevent the main thread from shutting down before the child thread is finished.


Complete Example

Here is a complete coded example showing how we can call a function from a new thread.

from threading import Thread

def bubbleSort(arr): 
    n = len(arr)
    for i in range(n-1): 
        for j in range(0, n-i-1): 
            if arr[j] > arr[j+1]: 
                arr[j], arr[j+1] = arr[j+1], arr[j]
    print(arr)

array = [8,6,0,9,4,2,8,4,3]

thread = Thread(target=bubbleSort, args=(array,))
thread.start()

# Main thread performing some other tasks
# e.g: I/O operations or other computation

thread.join()

The output:

[0, 2, 3, 4, 4, 6, 8, 8, 9]

This marks the end of the How to run a Function in a new Thread in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments