Python 多线程同步 把代码样例
时间: 2023-11-21 12:59:50 浏览: 43
下面是一个简单的 Python 多线程同步的代码样例,其中使用了 threading 模块和 Lock 对象:
```python
import threading
class Counter:
def __init__(self):
self.count = 0
self.lock = threading.Lock()
def increment(self):
with self.lock:
self.count += 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.count)
```
上述代码中,Counter 类包含一个计数器 count 和一个 Lock 对象,用于保护多个线程同时对计数器进行修改的情况。increment() 方法使用 with self.lock: 语句获取锁对象,确保在修改计数器时只有一个线程能够访问它。
worker() 函数是每个线程的入口点,它会多次调用 Counter 实例的 increment() 方法以增加计数器的值。
在主线程中,创建了 4 个子线程,每个子线程都会调用 worker() 函数。使用 join() 方法等待所有子线程执行完毕后,输出计数器的最终值。