Site Tools


import-threading

import threading

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.

Example

# 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()

Common classes and methods

  • threading.Thread(target, args): create thread
  • thread.start(): start thread execution
  • thread.join(): wait for thread to finish
  • thread.is_alive(): check if thread is running
  • threading.Lock(): mutual exclusion lock
  • threading.Event(): event signaling
  • threading.Condition(): condition variable
  • threading.current_thread(): get current thread
import-threading.md · Last modified: by 127.0.0.1