python time.sleep需要比预期更长的时间(多线程)

时间:2017-02-11 12:12:30

标签: python multithreading python-2.7 sleep

我已经查看了time.sleep()挂起/延迟的相关主题,但还没有找到答案。因此,用我正在看到的问题发布问题。

我无法访问完整的代码。这是我可以访问的代码段,并且看到了问题:

def my_debug(self, msg):
    logging.debug(msg, extra={'threadname':threading.currentThread().name})

while True:
    next = time.time() + INTERVAL # INTERVAL = 5
    my_debug("Triggering event")
    # some code
    # some more code
    sleep_time = max(next - time.time(), 0)
    my_debug("Sleeping for %d sec" % sleep_time)
    time.sleep(sleep_time)

这会产生:

2017-01-11 00:08:03 DEBUG MainThread Sleeping for 4 sec
2017-01-11 00:08:21 DEBUG MainThread Triggering event

显然,还有其他线程,而while循环在MainThread中执行。 time.sleep应该睡4秒钟,但最后等了18秒。

我正在寻找可能导致此行为的可能原因/方案。

任何帮助/指示都会非常感激。

1 个答案:

答案 0 :(得分:1)

这个捏造的例子可以重现你的结果。 另一个线程在计算和打印之间更改全局sleep_time。没有锁定:

import logging
import time
import threading


INTERVAL = 5

logging.basicConfig(filename='thread.log',level=logging.DEBUG,
                    format='%(asctime)s %(message)s')

def my_debug(msg):
    logging.debug(msg, extra={'threadname':threading.currentThread().name})


class Changer(threading.Thread):

    def run(self):
        global sleep_time
        while True:
            sleep_time = 18


changer = Changer()
changer.start()


while True:
    next = time.time() + INTERVAL # INTERVAL = 5
    my_debug("Triggering event")
    # some code
    # some more code
    sleep_time = max(next - time.time(), 0)
    my_debug("Sleeping for %f sec" % sleep_time)
    time.sleep(sleep_time)

thread.log的内容:

2017-02-11 19:45:14,700 Triggering event
2017-02-11 19:45:14,701 Sleeping for 4.999720 sec
2017-02-11 19:45:32,705 Triggering event
2017-02-11 19:45:32,705 Sleeping for 4.999525 sec
2017-02-11 19:45:50,710 Triggering event
2017-02-11 19:45:50,710 Sleeping for 4.999726 sec
2017-02-11 19:46:08,714 Triggering event
2017-02-11 19:46:08,716 Sleeping for 4.997533 sec
2017-02-11 19:46:26,720 Triggering event
2017-02-11 19:46:26,725 Sleeping for 4.995042 sec
2017-02-11 19:46:44,730 Triggering event
2017-02-11 19:46:44,731 Sleeping for 4.999471 sec
2017-02-11 19:46:49,730 Triggering event
2017-02-11 19:46:49,731 Sleeping for 4.999794 sec
2017-02-11 19:47:07,736 Triggering event
2017-02-11 19:47:07,736 Sleeping for 4.999609 sec
2017-02-11 19:47:25,739 Triggering event
2017-02-11 19:47:25,739 Sleeping for 4.999751 sec

请注意,我将wait格式化为float,以避免在输出中丢失近一秒。