【问题标题】:Python - start and stop multiple threadsPython - 启动和停止多个线程
【发布时间】:2014-05-04 16:38:43
【问题描述】:

我有三个函数,functionA、functionB 和 functionC。
我希望函数 A 和函数 B 同时运行,当函数 B 中的条件为真时,我希望函数 A 停止,函数 C 运行,然后函数 A 与函数 B 一起再次开始运行。

所以基本上,functionA 看起来像:

def functionA:
    while True:
        if condition == true:
            functionB.stop()
            functionC()

谁能帮我解决这个问题? 谢谢

【问题讨论】:

    标签: python multithreading function conditional-statements simultaneous


    【解决方案1】:

    使用并行编程,做事的方法总是不止一种。所以其他人可能对如何做到这一点有完全不同的想法。

    首先想到的方式是通过Event。保留其中三个,并根据需要打开/关闭它们。

    from threading import Thread, Event
    
    def worker1(events):
        a,b,c = events
        while True:
            a.wait() # sleep here if 'a' event is set, otherwise continue
    
            # do work here
    
            if some_condition:
                c.clear() # put c to sleep
                b.set() # wake up, b    
    
    def worker2(events):
        a,b,c = events
        while True:
            b.wait() 
            #do work
            if some_condition:
                a.clear()
                c.set()
    
    def worker3(events):
        a,b,c = events
        while True:
            c.wait() 
            #do work
            if some_condition:
                b.clear()
                a.set()
    

    然后启动它们:

    events = [Event() for _ in range(3)]
    events[0].set()
    events[1].set()
    #events[2] starts un-set, i.e. worker3 sleeps at start
    
    threads = []
    threads.append(Thread(target=worker1, args=(events,)))
    threads.append(Thread(target=worker2, args=(events,)))
    threads.append(Thread(target=worker3, args=(events,)))
    
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    

    未经测试的粗略代码,比它需要的更冗长(你可以用一个工人 def 编写这一切,需要一些额外的参数),但希望你能走上正确的道路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多