在 python 中如何让一个线程休眠而其他线程 运行

How can I make one thread sleep while the others run in python

我是多线程的新手,一直在尝试在后台为我的一个程序创建一个计时器,同时其他几个线程执行它们的代码。我目前的代码设置如下:

def timer(length):
    global kill
    kill = False
    print('Timer starting!')
    for i in range(length):
        time.sleep(1)
    kill = True

def r(interval, id):
    print(id, "running")
    while True:
        if kill:
            break
        time.sleep(interval)
        print(f'{id}: {time.localtime()}')

timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))

threads = [timerThread, runThread1, runThread2]

timerThread.start()
runThread1.start()
runThread2.start()

for t in threads:
    t.join()

显然,这不是一个有用的程序(只是为了帮助我学习线程模块的基础知识),但我仍然需要知道如何解决这个问题。我 95% 确定问题是由在计时器函数中使用“time.sleep(1)”引起的,但我不知道使用只会影响一个线程的替代方法。如果有任何建议,我将不胜感激。

你在调用你的函数之前你甚至创建线程:

timerThread = threading.Thread(target = timer(15))
runThread1 = threading.Thread(target = r(2, "thread1"))
runThread2 = threading.Thread(target = r(5, "thread2"))

您需要传递一个可调用的 target 而不是已经调用它的结果; args可以单独传:

timerThread = threading.Thread(target=timer, args=(15,))
runThread1 = threading.Thread(target=r, args=(2, "thread1"))
runThread2 = threading.Thread(target=r, args=(5, "thread2"))