0
点赞
收藏
分享

微信扫一扫

一个多线程任务流程控制

import threading


class Que_test:
    def __init__(self):
        # 创建条件变量和计数器
        self.cv = threading.Condition()
        self.counter = 1

    def first(self):
        with self.cv:
            print('first')
            self.counter += 1
            self.cv.notify_all()

    def second(self):
        with self.cv:
            while self.counter != 2:
                self.cv.wait()
            print('second')
            self.counter += 1
            self.cv.notify_all()

    def third(self):
        with self.cv:
            while self.counter != 3:
                self.cv.wait()
            print('third')
            self.counter += 1
            self.cv.notify_all()

    def fourth(self):
        with self.cv:
            while self.counter != 4:
                self.cv.wait()
            print('fourth')

    def maindo(self):
        threads = [
            threading.Thread(target=self.first),
            threading.Thread(target=self.second),
            threading.Thread(target=self.third),
            threading.Thread(target=self.fourth),
        ]
        for target in threads:
            target.start()
        for target in threads:
            target.join()


if __name__ == '__main__':
    t = Que_test()
    t.maindo()

作用:控制任务按序运行

使用方法:在print处修改成你的任务事件

运行截图:

一个多线程任务流程控制_条件变量

举报

相关推荐

0 条评论