Python暂停线程,手动完成并重置时间

时间:2016-08-01 09:15:42

标签: python multithreading

我需要每x秒调用一次函数,但可以选择手动调用它,在这种情况下重置时间。我是这样的:

import time
import threading

def printer():
    print("do it in thread")

def do_sth(event):
    while not event.is_set():
        printer()
        time.sleep(10)

event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
t.daemon = True
t.start()
a = input()
if a == 't':
    event.set()
elif a == 'm':
    event.wait()
    printer()
    event.clear()

更新: 我发现了一些对我很有帮助的东西:Python - Thread that I can pause and resume 现在我的代码看起来像这样:

import threading, time, sys

class ThreadClass(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.can_run = threading.Event()
        self.thing_done = threading.Event()
        self.thing_done.set()
        self.can_run.set()

    def run(self):
        while True:
            self.can_run.wait()
            try:
                self.thing_done.clear()
                self.do_in_thread()
            finally:
                self.thing_done.set()
            time.sleep(5)

    def pause(self):
        self.can_run.clear()
        self.thing_done.wait()

    def resume(self):
        self.can_run.set()

    def do_in_thread(self):
        print("Thread...1")
        time.sleep(2)
        print("Thread...2")
        time.sleep(2)
        print("Thread...3")


def do_in_main():
    print("Main...1")
    time.sleep(2)
    print("Main...2")
    time.sleep(2)
    print("Main...3")

if __name__ == '__main__':

    t = ThreadClass()
    t.daemon = True
    t.start()
    while True:
        i = input()
        if i == 'm':
            t.pause()
            do_in_main()
            t.resume()
        elif i == 't':
            sys.exit()
            # t.join()

唯一的问题是,当我终止时,希望线程在退出之前完成其工作。

1 个答案:

答案 0 :(得分:0)

可能是缓冲输出是罪魁祸首,因此 - 你正在获得预期的行为。

我将您的代码更改为以下内容,似乎有所作为(如果这是您想要的,取决于您):

import time
import threading

def printer():
    print("do it in thread")

def do_sth(event):
    print("event.is_set:", event.is_set())
    while not event.is_set():
        printer()
        time.sleep(10)

event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
print("t:",t)
t.daemon = True
t.start()
a = input()
if a == 't':
    event.set()
elif a == 'm':
    event.wait()
    printer()
    event.clear()