python线程和线程锁的使用
时间: 2023-08-09 16:09:12 浏览: 44
在Python中,要使用线程,可以使用内置的`threading`模块。其中,最重要的是Thread类,可以通过实例化Thread类来创建一个新的线程。
使用线程锁的目的是为了避免多个线程同时修改某个共享资源而导致的数据不一致问题。Python中的线程锁可以通过`threading`模块中的Lock类来实现。
下面是一个简单的示例代码,演示了如何使用线程和线程锁:
```python
import threading
class Counter:
def __init__(self):
self.value = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.value += 1
def worker(counter):
for i in range(10000):
counter.increment()
counter = Counter()
threads = []
for i in range(4):
t = threading.Thread(target=worker, args=(counter,))
threads.append(t)
t.start()
for t in threads:
t.join()
print(counter.value) # 输出40000
```
在这个示例中,我们定义了一个Counter类,并在其中定义了一个increment方法,用于将value属性加1。在increment方法中,我们使用了with语句和Lock类来实现线程锁。这样,在多个线程同时调用increment方法时,每次只有一个线程能够获取到锁,从而避免了多个线程同时修改value属性的问题。
接下来,我们创建了4个线程,并让它们同时调用worker函数,传入Counter对象作为参数。在worker函数中,每个线程都会调用Counter对象的increment方法,这样就可以模拟多个线程同时对Counter对象进行操作的情况。
最后,我们在主线程中等待所有子线程执行完毕,并输出Counter对象的value属性,可以看到输出的结果为40000,说明线程锁生效了。