Create and Start a Python Thread with Examples: A Beginner Tutorial – Python Tutorial

By | December 16, 2019

Python thread is widely used in python application, which is also an advanced tip for python beginners. In this tutorial, we will write some simple examples to  introduce how to create and start to run a python thread for python beginners.

Preliminary

To use thread in python, you shoud import threading library.

import threading
import time

How to create a python thread?

We can use threading.Thread() to create a thread object in python.

threading.Thread(target=function_name, args)

where function_name is the name of a function, which can be run in a python thread. args contains some parameters that will be passed into function_name.

We will use a example to show you how to do.

Create a function will be run in a python thread

def test(name, a, b):
    print("run thread "+ name)
    print(a + b)
    print("thread " + name + " is finished")

We will make test(name, a, b) function run in a python thread, this function will receive three parameters.

Bind a function to a python thread

thread_name = 'compute' 
th = threading.Thread(target=test, args=[thread_name, 2, 3])

We use threading.Thread() to bind test() function and pass three parameters to it. Finally, we will use th to save the thread object.

Start and run thread

th.start() 
th.join()

We can use thread.start() to start a python thread.

Run this python script, we will get result like:

run threadtest 1
5
thread test 1 is finished

We can find test() function is run in a python thread. We create and run a python thread successfully.

To understand thread.join() function, you can view this tutorial.

Understand join() in Python Threading with Examples: A Beginner Guide – Python Tutorial

Leave a Reply

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