defworker(identifier): print(f"Worker {identifier} is waiting to access the resource.") with semaphore: print(f"Worker {identifier} has acquired the semaphore.") time.sleep(2) # 模拟资源处理过程 print(f"Worker {identifier} is releasing the semaphore.")
# 创建多个线程 threads = [] for i inrange(5): thread = threading.Thread(target=worker, args=(i,)) threads.append(thread) thread.start()
deflock_worker(identifier): print(f"Worker {identifier} is trying to acquire the lock.") lock.acquire() # 请求获取锁 try: print(f"Worker {identifier} has acquired the lock.") time.sleep(2) finally: print(f"Worker {identifier} is releasing the lock.") lock.release()
defsemaphore_worker(identifier): print(f"Worker {identifier} is trying to acquire the semaphore.") semaphore.acquire() # 请求获取信号量 try: print(f"Worker {identifier} has acquired the semaphore.") time.sleep(2) finally: print(f"Worker {identifier} is releasing the semaphore.") semaphore.release()
# 创建线程 lock_threads = [] for i inrange(3): thread = threading.Thread(target=lock_worker, args=(i,)) lock_threads.append(thread) thread.start()
# 等待所有Lock线程完成 for thread in lock_threads: thread.join()
print("All Lock workers have finished.")
# 创建Semaphore线程 semaphore_threads = [] for i inrange(5): thread = threading.Thread(target=semaphore_worker, args=(i,)) semaphore_threads.append(thread) thread.start()
# 等待所有Semaphore线程完成 for thread in semaphore_threads: thread.join()
defworker(identifier): print(f"Worker {identifier} is trying to acquire the semaphore.") semaphore.acquire() # 手动获取信号量 try: print(f"Worker {identifier} has acquired the semaphore.") # 可能在这里做一些操作 time.sleep(1) if identifier == 1: print(f"Worker {identifier} needs to do something and will release the semaphore.") # 在此释放信号量,但并不做完整的操作 semaphore.release() return# 提前返回 # 完成其他操作 print(f"Worker {identifier} has completed its task.") finally: # 这里,以保障最后总会释放信号量 semaphore.release() # 确保最后释放信号量
# 启动多个线程 threads = [] for i inrange(3): thread = threading.Thread(target=worker, args=(i,)) threads.append(thread) thread.start()
# 等待所有线程完成 for thread in threads: thread.join()
print("All workers have finished.")
在这个示例中,信号量的释放并不是总是在一个统一的代码块中完成的,因此没有使用 with 语句。而是用 try…finally 确保资源在不论何种情况下都能被释放。
而当资源的使用在一段逻辑中是连续的且不易引发异常,使用 with 语句会更简洁和安全。选择合适的资源管理方式,能提高代码的可读性和可维护性。 在Python的threading模块中,Condition对象是一种用于线程间同步的原语,通常用于一种生产者-消费者模式。它允许一个或多个线程通过条件变量协调其执行。条件变量是用来实现线程间的通信和同步的机制。