之前我们在多线程那一节中看了一个由于存在全局变量资源竞争造成的100万bug,这节我们看一下如何使用队列来改进此Bug,
from threading import Thread,Lock
from queue import Queue
number = 0
q = Queue(2)
q.put(number)
def work1():
global number
for i in range(1000000):
number = q.get()
number += 1
q.put(number)
def work2():
for i in range(1000000):
number = q.get()
number += 1
q.put(number)
def main():
t1 = Thread(target=work1)`在这里插入代码片`
t2 = Thread(target=work2)
t1.start()
t2.start()
#等待主线程
t1.join()
t2.join()
print(q.get())
if __name__ =='__main__':
main()
运行结果:
2000000
可以看出使用队列也可以改进该bug,但是执行速度慢了很多,
因为队列中读取数据和存放数据都比较浪费时间;