[Python] 纯文本查看 复制代码 import threading
import 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[threading.Lock], current:int, then:int) -> None:
with locks[current]:
tp.pa()
try:
locks[then].release()
except RuntimeError:
pass
def trunb(tp:TPrint, locks:typing.Sequence[threading.Lock], current:int, then:int) -> None:
with locks[current]:
tp.pb()
try:
locks[then].release()
except RuntimeError:
pass
def trunc(tp:TPrint, locks:typing.Sequence[threading.Lock], current:int, then:int) -> None:
with locks[current]:
tp.pc()
try:
locks[then].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([ta,tb,tc])
tc.start()
tb.start()
ta.start()
locks[0].release()
ta.join()
tb.join()
tc.join()
输出日志:
- --->>> A <<<---
- --->>> B <<<---
- --->>> C <<<---
|