简体   繁体   English

时间.睡眠()function

[英]time.sleep() function

I am just trying to understand that if when I call time.sleep(x), the current thread that is running the code gets delayed by x seconds.我只是想了解,如果当我调用 time.sleep(x) 时,运行代码的当前线程会延迟 x 秒。 But does that free up the processor for those x seconds or does the thread keep the resources to itself and after x seconds it just starts executing the next lines of code.但是,这会在 x 秒内释放处理器,还是线程将资源保留给自己,并在 x 秒后才开始执行下一行代码。

Editing with the exact scenario I am facing:使用我面临的确切场景进行编辑:

Here's the case with me:这是我的情况:

class SomeHandler(tornado.websocket.WebSocketHandler)
  @tornado.gen.coroutine
  def something_async():
    time.sleep(5)
    return result

  def on_message(message):
    future = yield something_async(message)

if __name__ == '__main__':
  application = tornado.web.Application([
    (r'/', SomeHandler),
  ])

  http_server = tornado.httpserver.HTTPServer(application)
  http_server.listen(8888)
  tornado.ioloop.IOLoop.instance().start()

Now since this Tornado will be a single threaded server, What exactly does time.sleep(5) do in this case (will it just block the thread for 5 seconds making the whole process synchronous) or the coroutine spawns a new thread?现在,由于这个 Tornado 将是一个单线程服务器,time.sleep(5) 在这种情况下到底做了什么(它会阻塞线程 5 秒,使整个进程同步)还是协程生成一个新线程?

An example is always best: 一个例子总是最好的:

#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
from __future__ import (absolute_import, division, print_function)
#                        unicode_literals)

import threading
import time


def func1():
    time.sleep(10)
    print('Func1: Out of sleep and returning')


def func2(flag):
    while not flag:
        time.sleep(1)
        print('Func2: looping')

    print('Func2: Flag set, leaving')


t1 = threading.Thread(target=func1)
f = list()

t2 = threading.Thread(target=func2, kwargs=dict(flag=f))

t1.start()
t2.start()

t1.join()
f.append(None)

With output: 输出:

Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func2: looping
Func1: Out of sleep and returning
Func2: looping
Func2: Flag set, leaving

It should be obvious from the output that even if t1 (the 1st thread) is blocked in a long time.sleep of 10 seconds, the 2nd thread t2 is running. 从输出中可以明显看出,即使t1 (第一个线程)长时间处于阻塞状态, time.sleep 10秒,第二个线程t2运行。

And even when t1 is done we see that the main thread is able to append to the list which is being used as a flag to let t2 understand it has to return and therefore end. 即使完成了t1 ,我们仍然可以看到主线程能够append到列表中,该列表被用作flag以使t2了解它必须返回并因此结束。

So: time.sleep only blocks the thread in which is being executed. 因此: time.sleep仅阻塞正在执行该线程的线程。

Tornado never spawns a thread for you.* If you call time.sleep, it blocks the entire process for the duration of the sleep; 龙卷风从不为您生成线程。*如果您调用time.sleep,它将在整个睡眠期间阻止整个过程; no other processing proceeds. 没有其他处理继续。 This is why the docs say "time.sleep should not be used in coroutines because it is blocking" . 这就是为什么文档说“ time.sleep不应该在协程中使用,因为它正在阻塞”的原因 To explicitly pause a coroutine and return control to the IOLoop so other processing can proceed: 要显式暂停协程并将控制权返回给IOLoop,以便可以进行其他处理:

yield gen.sleep(0.5)

* Tornado can spawn threads for DNS resolution or when you explicitly use a ThreadPoolExecutor to make a task asynchronous. *龙卷风可以生成线程以进行DNS解析,或者在您显式使用ThreadPoolExecutor使任务异步时。 But you can ignore these cases for this discussion. 但是您可以在此讨论中忽略这些情况。

you can use the code inside function:你可以使用function里面的代码:

import time
time.sleep(2) # put value here as seconds, 2 is 2 seconds

OR或者

from time import sleep
sleep(60) # put value here as seconds, 60 is 60 seconds = 1 minute

Example code:示例代码:

import time
def function1():
    print('function1 is sleeping for 2 seconds...')
    time.sleep(2)

count = 0
while True:
    if count >= 10:
        break
    function1()
    count=count+1

For further details please visit: https://docs.python.org/3/library/time.html#time.sleep更多详情请访问: https://docs.python.org/3/library/time.html#time.sleep

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM