有没有办法让线程从线程外部进入休眠状态?

时间:2016-11-15 07:40:51

标签: python

import time
import threading


def do_something():
    while True:
        time.sleep(0.5)
        print('I am alive')


def main():
    while True:
        time.sleep(1)
        print('Hello')


daemon_thread = threading.Thread(target=do_something, daemon=True)
daemon_thread.start()
main()

我有没有办法让daemon_threaddo_something()之外的3 {秒}进入睡眠状态?我的意思是假设daemon_thread.sleep(3)

1 个答案:

答案 0 :(得分:1)

创建一个计数器半秒钟,然后使计数器的休眠函数递增:

lock = Lock()
counter = 0


def do_something():
    global counter
    while True:
        time.sleep(0.5)
        with lock:
            if counter == 0:
                print('I am alive')
            else:
                counter -= 1


def increment(seconds):
    global counter
    with lock:
        counter += 2*seconds


# after starting thread

increment(3)  # make the thread wait three seconds before continuing
相关问题