在Python中,可以使用threading
模块来实现多线程共享变量。
下面是一个简单的例子,展示了如何使用多线程共享变量:
import threading # 全局变量 counter = 0 def increment(): global counter for _ in range(100000): # 对共享变量加锁 with lock: counter += 1 # 创建锁对象 lock = threading.Lock() # 创建两个线程 thread1 = threading.Thread(target=increment) thread2 = threading.Thread(target=increment) # 启动线程 thread1.start() thread2.start() # 等待线程结束 thread1.join() thread2.join() # 打印最终结果 print("Counter: ", counter)
在这个例子中,我们定义了一个全局变量counter
,并创建了两个线程来对其进行操作。increment
函数会循环100000次,并在每次循环中使用with lock
语句对共享变量进行加锁,以确保在修改共享变量时不会发生竞争条件。
在主线程中,我们启动了两个线程,并使用join
方法等待它们的结束。最后,我们打印出最终的计数器值。
需要注意的是,在多线程编程中,共享变量的并发访问可能导致竞争条件,因此需要使用锁或其他同步机制来保证共享变量的一致性。在Python中,threading.Lock
对象可以用来创建锁,并使用with
语句来自动管理锁的获取和释放。