python双线程的线程锁
时间: 2023-08-18 21:13:04 浏览: 53
在 Python 中,可以使用线程锁来确保在多个线程中对共享资源的访问是同步的。线程锁可以通过 `threading` 模块中的 `Lock` 类来实现。
下面是一个简单的示例代码,演示了如何在 Python 中使用线程锁:
```python
import threading
# 创建一个线程锁
lock = threading.Lock()
# 共享资源
counter = 0
# 线程函数
def increment():
global counter
for _ in range(100000):
# 获取线程锁
lock.acquire()
try:
# 对共享资源进行操作
counter += 1
finally:
# 释放线程锁
lock.release()
# 创建两个线程
thread1 = threading.Thread(target=increment)
thread2 = threading.Thread(target=increment)
# 启动线程
thread1.start()
thread2.start()
# 等待线程完成
thread1.join()
thread2.join()
# 打印最终结果
print("Counter:", counter)
```
在上面的示例中,我们创建了一个线程锁 `lock`,并将共享资源 `counter` 初始化为 0。然后,我们定义了一个 `increment` 函数,该函数会在循环中对 `counter` 进行递增操作。在每次操作之前,我们使用 `lock.acquire()` 获取线程锁,并在操作完成后使用 `lock.release()` 释放线程锁。
最后,我们创建了两个线程,并启动它们来执行 `increment` 函数。等待两个线程完成后,我们打印最终结果。
通过使用线程锁,我们可以确保在任意时刻只有一个线程可以访问共享资源,从而避免了竞态条件和数据不一致的问题。