在循环中使用sleep()可以很好吗?

eug*_*ene 0 python multithreading sleep loops

我无法更好地描述这个问题.

这是来自redis-py github页面.

>>> while True:
>>>     message = p.get_message()
>>>     if message:
>>>         # do something with the message
>>>     time.sleep(0.001)  # be nice to the system :)
Run Code Online (Sandbox Code Playgroud)

我认为这种编码风格(在循环中睡觉)并不是那么好,但这个库让我别无选择,只能使用这种风格.(至少他们这样建议)

这可以忍受吗?

https://github.com/andymccurdy/redis-py

Car*_*ten 5

在这种情况下无需睡觉!文档字符串get_message表示您可以指定timeout参数,函数将timeout在返回之前等待几秒钟.

while True:
    message = p.get_message(timeout=0.1) # or however long you'd want to wait
    if message:
        # do something with the message
Run Code Online (Sandbox Code Playgroud)

如果您不坚持使用get_message,则会有一种listen方法,该方法将阻止,直到下一条消息到达.实际上,它的用法在您发布的代码示例正下方的项目的Github页面上进行了解释.它只是像任何其他迭代器一样使用:

for message in p.listen():
    # do something with the message
Run Code Online (Sandbox Code Playgroud)

  • timeout参数在master分支中,但不在最新的稳定版2.10.3(pip install)中..很高兴知道! (2认同)