在Python中,等待(wait)通常与线程(threading)模块一起使用。以下是一些关于Python线程等待的技巧:
-
使用
threading.Event
:threading.Event
对象可以用于线程间的简单信号通知。它有一个set()
方法用于发出信号,一个is_set()
方法用于检查信号是否已发出,以及一个wait()
方法用于阻塞线程直到信号被发出。import threading event = threading.Event() def worker(): print("Worker thread started") event.wait() # 阻塞线程直到事件被设置 print("Worker thread finished") thread = threading.Thread(target=worker) thread.start() event.set() # 发出信号,唤醒等待的线程 thread.join()
-
使用
threading.Condition
:threading.Condition
对象允许一个或多个线程等待某个条件成立。它提供了wait()
方法用于阻塞线程直到条件被满足,以及notify()
或notify_all()
方法用于唤醒等待的线程。import threading condition = threading.Condition() data = https://www.yisu.com/ask/[]"Worker thread started") while not data: # 如果数据为空,则等待 condition.wait() print(f"Worker thread processed {data[0]}") data.pop(0) condition.notify_all() # 唤醒所有等待的线程 threads = [threading.Thread(target=worker) for _ in range(5)] for thread in threads: thread.start() for item in range(5): with condition: data.append(item) condition.notify_all() # 唤醒所有等待的线程 for thread in threads: thread.join()
-
使用
threading.Semaphore
:threading.Semaphore
对象用于限制同时访问共享资源的线程数量。它提供了acquire()
和release()
方法,分别用于尝试获取信号量和释放信号量。当信号量的计数器为零时,线程将被阻塞直到其他线程释放信号量。import threading semaphore = threading.Semaphore(3) # 最多允许3个线程同时访问 def worker(thread_id): with semaphore: print(f"Worker thread {thread_id} started") print(f"Worker thread {thread_id} finished") threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)] for thread in threads: thread.start() for thread in threads: thread.join()
-
使用
threading.Lock
:threading.Lock
对象用于确保同一时间只有一个线程可以访问共享资源。它提供了acquire()
和release()
方法,分别用于尝试获取锁和释放锁。当锁被其他线程持有时,线程将被阻塞直到锁被释放。import threading lock = threading.Lock() shared_resource = 0 def worker(thread_id): global shared_resource with lock: print(f"Worker thread {thread_id} started") shared_resource += 1 print(f"Worker thread {thread_id} finished, shared_resource = {shared_resource}") threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)] for thread in threads: thread.start() for thread in threads: thread.join()
这些技巧可以帮助您更有效地使用Python的线程等待功能。在实际应用中,您可能需要根据具体需求选择合适的同步原语(如Event
、Condition
、Semaphore
或Lock
)。