import threading
# 创建一个锁对象
lock = threading.Lock()
# 定义一个需要线程安全的函数
def thread_safe_function():
global shared_resource
with lock: # 使用with语句自动获取和释放锁
temp = shared_resource
temp += 1
shared_resource = temp
print(f"Thread {threading.current_thread().name} updated shared_resource to {shared_resource}")
# 共享资源
shared_resource = 0
# 创建多个线程
threads = []
for i in range(5):
thread = threading.Thread(target=thread_safe_function, name=f"Thread-{i+1}")
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print(f"Final value of shared_resource: {shared_resource}")
threading
模块用于创建和管理线程。lock = threading.Lock()
创建一个锁对象,用于确保同一时间只有一个线程可以访问共享资源。thread_safe_function
是一个示例函数,它会更新一个全局变量 shared_resource
。使用 with lock:
语句块来确保在该代码块内只有一个线程可以执行。shared_resource
是一个全局变量,多个线程会尝试同时修改它。threading.Thread
创建多个线程,并将它们添加到 threads
列表中。每个线程都会调用 thread_safe_function
。thread.join()
确保主线程等待所有子线程完成后再继续执行。shared_resource
值。这样可以确保即使多个线程并发执行,共享资源也不会出现竞争条件(race condition)。
上一篇:python中try
下一篇:conda更新python版本
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站