吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1098|回复: 4
收起左侧

[学习记录] Python 多线程顺序打印的一种解决方法

[复制链接]
Cool_Breeze 发表于 2022-12-8 11:13
[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 <<<---

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

xu2006 发表于 2022-12-8 12:32
谢谢分享
Vvvvvoid 发表于 2022-12-8 13:57
wuaikirin 发表于 2022-12-8 14:19
yllen 发表于 2022-12-8 17:57
wuaikirin 发表于 2022-12-8 14:19
上了锁不如直接用单线程

是的,多线程加锁就没啥意义了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-25 04:54

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表