Skip to content

Creating and Starting Threads

Basic Thread usage

basic_thread.py
import threading
 
 
def greet(name: str) -> None:
    print("Hello", name)
 
 
t = threading.Thread(target=greet, args=("Ravi",))
t.start()
t.join()
print("Main thread finished")
basic_thread.py
import threading
 
 
def greet(name: str) -> None:
    print("Hello", name)
 
 
t = threading.Thread(target=greet, args=("Ravi",))
t.start()
t.join()
print("Main thread finished")

Naming threads

Naming is helpful for logs.

thread_name.py
import threading
 
 
def work():
    print("Running in:", threading.current_thread().name)
 
 
t = threading.Thread(target=work, name="worker-1")
t.start()
t.join()
thread_name.py
import threading
 
 
def work():
    print("Running in:", threading.current_thread().name)
 
 
t = threading.Thread(target=work, name="worker-1")
t.start()
t.join()

Common mistakes

1) Forgetting join()

If you don’t join()join(), the main program may exit early in some cases.

2) Sharing data without protection

Threads share memory. You need locks (next pages).

πŸ§ͺ Try It Yourself

Exercise 1 – Create a Simple Thread

Exercise 2 – Join a Thread

Exercise 3 – Run Multiple Threads

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did