import threading def task(): for i in range(10): print("I am running in a thread") t1 = threading.Thread(target=task) t2 = threading.Thread(target=task) t1.start() t2.start()
import threading def task(num): print("Task:", num) threads = [] for i in range(5): t = threading.Thread(target=task, args=(i,)) threads.append(t) t.start() for t in threads: t.join()
import threading count = 0 lock = threading.Lock() def increment(): global count with lock: count += 1 print(f"Count is now {count}") threads = [] for i in range(5): t = threading.Thread(target=increment) threads.append(t) t.start() for t in threads: t.join()In all these examples, Python threading package library is used to create and manage threads in Python.