1. Importing Required Modules
import threading
import time
2. Creating and Starting Threads
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
t = threading.Thread(target=print_numbers)
t.start()
t.join() # Wait for thread to finish
3. Passing Arguments to Threads
def greet(name):
print(f"Hello, {name}")
t = threading.Thread(target=greet, args=("Alice",))
t.start()
4. Using Thread Subclasses
class MyThread(threading.Thread):
def run(self):
print("Thread running")
t = MyThread()
t.start()
5. Daemon Threads
t = threading.Thread(target=print_numbers)
t.daemon = True # Thread will close when the main program exits
t.start()
6. Synchronization with Lock
lock = threading.Lock()
def critical_section():
with lock:
print("Locked section")
7. Using RLock (Reentrant Lock)
rlock = threading.RLock()
def task():
with rlock:
with rlock: # Safe nested locking
print("Nested lock allowed")
8. Using Condition Variables
condition = threading.Condition()
def consumer():
with condition:
condition.wait()
print("Resource consumed")
def producer():
with condition:
print("Producing resource")
condition.notify()
9. Thread-safe Queue
from queue import Queue
q = Queue()
def producer():
q.put(10)
def consumer():
item = q.get()
print(item)