Advertisement
Beginner Python, Concurrency (asyncio/threading/multiprocessing)

How do you create and run a basic thread using the threading module?

Short answer

Create a threading.Thread object, passing the target function (and optional args), then call .start() to begin execution concurrently, and .join() to wait for it to finish before continuing.

Save Python mock interview
Advertisement
AModel answer
Create a threading.Thread object, passing the target function (and optional args), then call .start() to begin execution concurrently, and .join() to wait for it to finish before continuing.
import threading

def greet(name):
    print(f"Hello, {name}!")

thread = threading.Thread(target=greet, args=("Sam",))
thread.start()
thread.join()  # waits for the thread to finish
Real-world example
Running a background task (like a periodic health check) concurrently with the main program's execution.
Likely follow-ups
  • What happens to the main program if it exits before a non-daemon thread finishes?
Related topics