Python 多线程顺序打印的一种解决方法
import threadingimport typing
class TPrint(object):
def pa(self) -> None:
print("--->>> A <<<---")
def pb(self) -> None:
print("--->>> B <<<---")
def pc(self) -> None:
print("--->>> C <<<---")
def truna(tp:TPrint, locks:typing.Sequence, current:int, then:int) -> None:
with locks:
tp.pa()
try:
locks.release()
except RuntimeError:
pass
def trunb(tp:TPrint, locks:typing.Sequence, current:int, then:int) -> None:
with locks:
tp.pb()
try:
locks.release()
except RuntimeError:
pass
def trunc(tp:TPrint, locks:typing.Sequence, current:int, then:int) -> None:
with locks:
tp.pc()
try:
locks.release()
except RuntimeError:
pass
if __name__ == "__main__":
wait_list = []
locks = [ threading.Lock() for _ in range(3) ]
for n in locks: n.acquire()
pp = TPrint()
ta = threading.Thread(target=truna,args=(pp,locks, 0, 1))
tb = threading.Thread(target=trunb,args=(pp,locks, 1, 2))
tc = threading.Thread(target=trunc,args=(pp,locks, 2, 0))
wait_list.extend()
tc.start()
tb.start()
ta.start()
locks.release()
ta.join()
tb.join()
tc.join()
输出日志:
[*]--->>> A <<<---
[*]--->>> B <<<---
[*]--->>> C <<<---
谢谢分享 可以用 join 方法把
上了锁不如直接用单线程 wuaikirin 发表于 2022-12-8 14:19
上了锁不如直接用单线程
是的,多线程加锁就没啥意义了
页:
[1]