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 coffeeWas this page helpful?
Let us know how we did
