Python 中的线程模块提供了一个高级接口来创建和管理线程,使您能够并发运行代码。这对于可以并行执行的任务(例如 I/O 密集型操作)特别有用。下面列出了 threading 模块中常用的方法和函数,并附有简短的示例。
Thread 类是线程模块的核心。您可以使用此类创建和启动新线程。
import threading def print_numbers(): for i in range(5): print(i) t = threading.Thread(target=print_numbers) t.start() # Starts a new thread t.join() # Waits for the thread to finish
启动线程的活动。
t = threading.Thread(target=print_numbers) t.start() # Runs the target function in a separate thread
阻塞调用线程,直到调用 join() 方法的线程终止。您可以选择指定超时。
t = threading.Thread(target=print_numbers) t.start() t.join(2) # Waits up to 2 seconds for the thread to finish
如果线程仍在运行,则返回 True。
t = threading.Thread(target=print_numbers) t.start() print(t.is_alive()) # True if the thread is still running
返回当前Thread对象,代表调用线程。
import threading def print_current_thread(): print(threading.current_thread()) t = threading.Thread(target=print_current_thread) t.start() # Prints the current thread info
返回当前活动的所有 Thread 对象的列表。
t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_numbers) t1.start() t2.start() print(threading.enumerate()) # Lists all active threads
返回当前存活的Thread对象的数量。
print(threading.active_count()) # Returns the number of active threads
Lock 对象是一个原始锁,用于防止竞争条件。您可以使用它来确保一次只有一个线程访问共享资源。
lock = threading.Lock() def thread_safe_function(): with lock: # Acquires the lock # Critical section print("Thread-safe code") t = threading.Thread(target=thread_safe_function) t.start()
可重入锁允许线程多次 acquire() 锁,而不会阻塞自身。
lock = threading.RLock() def reentrant_function(): with lock: with lock: # Same thread can acquire the lock again print("Reentrant lock example") t = threading.Thread(target=reentrant_function) t.start()
Condition 对象允许线程等待满足某些条件。
condition = threading.Condition() def thread_wait(): with condition: condition.wait() # Wait for the condition print("Condition met") def thread_notify(): with condition: condition.notify() # Notify the waiting thread t1 = threading.Thread(target=thread_wait) t2 = threading.Thread(target=thread_notify) t1.start() t2.start()
Event 对象用于在线程之间发出信号。一个线程可以等待事件被设置,另一个线程可以设置事件。
event = threading.Event() def wait_for_event(): event.wait() # Wait until the event is set print("Event has been set") t = threading.Thread(target=wait_for_event) t.start() event.set() # Set the event to allow the thread to continue
信号量对象允许您限制可以同时访问资源的线程数量。
semaphore = threading.Semaphore(2) # Only 2 threads can access the resource at once def access_resource(): with semaphore: print("Resource accessed") t1 = threading.Thread(target=access_resource) t2 = threading.Thread(target=access_resource) t3 = threading.Thread(target=access_resource) t1.start() t2.start() t3.start()
定时器线程在指定的时间间隔后执行函数。
def delayed_function(): print("Executed after delay") timer = threading.Timer(3, delayed_function) timer.start() # Executes `delayed_function` after 3 seconds
守护线程在后台运行,并在主程序退出时自动退出。您可以通过调用 setDaemon(True) 或将 daemon=True 传递给 Thread 构造函数来使线程成为守护进程。
t = threading.Thread(target=print_numbers, daemon=True) t.start() # Daemon thread will exit when the main program ends
threading 模块是 Python 中处理并发的强大工具。它提供了多个类和方法来创建和控制线程,从而可以轻松并行执行代码。从使用基本的 Thread 对象到使用 Lock 和 Semaphore 管理同步,该模块对于编写并发 Python 程序至关重要。
以上是Python 线程模块快速指南及示例的详细内容。更多信息请关注PHP中文网其他相关文章!