对Thread不太熟悉的朋友,可先行翻阅这个:Python多线程之Thread类
尽管Thread之间实现了多线程 *** 作,但每个Thread.start()的调用仍然有先后顺序。
>>> def printN(n,name=None): ... for i in range(n): print(f"{name}:{i}") >>> def test(): ... th1 = Thread(target=printN, args=[3,'th1']) ... th2 = Thread(target=printN, args=[3,'th2']) ... th1.start() ... th2.start() ... >>> test() th1:0 th1:1 th1:2 th2:0 th2:1 >>> th2:2
这个测试比较极端,在th2还没开始的时候,th1已经结束了。
Barrier的作用,就是让多个Thread一起开始。其原理是,设置一个栅栏,当start的线程数不够的时候,就把这些线程挡住,直到线程数足够多的时候,再一起执行。
# 导入线程模块 from threading import Thread, Barrier >>> b = Barrier(3, action=lambda : print("threads start")) >>> def printN(n, name=None): ... print(f"{name} ready") ... b.wait(2) ... for i in range(n): print(f"{name}:{i}") ... >>> def test(): ... thName = ['th1','th2','th3'] ... for i in range(3): ... th = Thread(target=printN, args=[5,thName[i]]) ... th.start() ... >>> test() th1 ready th2 ready th3 ready threads start #执行Barrier中的Action th3:0 th3:1 th2:0 th1:0 th1:1 th2:1 th2:2 th2:3 th2:4 th3:2 th3:3 th3:4 th1:2 th1:3 th1:4
其中,Barrier的构造函数有三个参量,分别代表阻塞线程数目parties、线程执行之前的执行函数Action以及延时时间。
Barrier类中最重要的函数就是wait,其中的参数代表当前线程的延时时间,如果不设置则表示一直等下去。wait相当于一个标记,当足够多的Barrier都已调用wait,则所有的wait在同一时间结束。
Barrier的运行机制就是,当多达parties个数的Barrier都已调用wait之后,则执行Action,然后终止等待,执行wait之后的内容。
除了wait,Barrier中还有一个reset函数比较重要,可以将当前已经调用wait的线程数置0。
可能是文化差异,Python标准库中很多本来就很直观的功能,偏偏要加上一些奇妙的比喻,反而显得画蛇添足了。而很多中文文档不知道是没看懂还是根本没看,不假思索地直译,甚至是机翻风格的直译,更让人费解。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)