import threading is a Python import that creates and manages threads for concurrent execution. Use threads to run multiple tasks simultaneously in a single process.
# Python # description: create and run threads import threading import time def worker(name, delay): time.sleep(delay) print(f"Worker {name} done") # Create threads t1 = threading.Thread(target=worker, args=("A", 1)) t2 = threading.Thread(target=worker, args=("B", 2)) # Start threads (runs concurrently) t1.start() t2.start() # Wait for threads to finish t1.join() t2.join() print("All workers done") # Thread with return value (using callable) class Worker: def __call__(self, name): print(f"Running {name}") t = threading.Thread(target=Worker(), args=("task",)) t.start() t.join()
threading.Thread(target, args): create threadthread.start(): start thread executionthread.join(): wait for thread to finishthread.is_alive(): check if thread is runningthreading.Lock(): mutual exclusion lockthreading.Event(): event signalingthreading.Condition(): condition variablethreading.current_thread(): get current thread