python给线程上锁
时间: 2023-10-16 12:22:22 浏览: 39
在 Python 中,可以使用 threading 模块来创建和管理线程。在多线程编程中,为了避免多个线程同时修改同一个共享资源而产生的数据竞争问题,可以使用锁机制来保证同一时间只有一个线程能够访问共享资源。
下面是一个使用锁的示例代码:
```python
import threading
# 定义一个共享资源
count = 0
# 创建一个锁
lock = threading.Lock()
# 定义一个线程函数
def increment():
global count
for i in range(1000000):
# 获取锁
lock.acquire()
try:
count += 1
finally:
# 释放锁
lock.release()
# 创建多个线程
threads = []
for i in range(10):
t = threading.Thread(target=increment)
threads.append(t)
# 启动线程
for t in threads:
t.start()
# 等待所有线程执行完毕
for t in threads:
t.join()
# 输出结果
print("count =", count)
```
在上面的代码中,我们先定义了一个共享资源 count,然后创建了一个锁 lock。在线程函数 increment 中,我们先获取锁,然后修改共享资源 count 的值,最后释放锁。这样就能够保证同一时间只有一个线程能够访问共享资源,从而避免了数据竞争问题的出现。