python time.sleep()函数

xa9qqrwz  于 2023-02-02  发布在  Python
关注(0)|答案(4)|浏览(195)

我只是想弄明白,如果我调用time.sleep(x),当前正在运行代码的线程会延迟x秒,但这是在这x秒内释放了处理器,还是线程将资源留给自己,x秒后就开始执行下一行代码。
根据我所面临的具体情况进行编辑:
我的情况是这样的:

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()

既然这个Tornado将是一个单线程服务器,那么time.sleep(5)在这种情况下究竟做了什么(它只是阻塞线程5秒钟,使整个进程同步),还是协程产生一个新线程?

j13ufse2

j13ufse21#

举个例子总是最好的:

#!/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)

输出:

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

从输出中可以明显看出,即使t1(第一个线程)在10秒的time.sleep长时间内被阻塞,第二个线程t2仍在运行。
甚至当t1完成时,我们看到主线程能够将append添加到用作flag的列表中,以让t2知道它必须返回并因此结束。
因此:time.sleep只阻塞正在其中执行的线程。

lmvvr0a8

lmvvr0a82#

Tornado从不为你生成线程。* 如果你调用time.sleep,它会在睡眠期间阻塞整个进程;没有其他处理继续进行。2这就是为什么文档说“time.sleep不应该在协程中使用,因为它阻塞了”。3要显式暂停协程并将控制返回IOLoop,以便其他处理可以继续进行:

yield gen.sleep(0.5)
  • Tornado可以为DNS解析或显式使用ThreadPoolExecutor使任务异步时生成线程,但在此讨论中可以忽略这些情况。
jw5wzhpr

jw5wzhpr3#

    • 您可以使用函数内的代码:**
import time
time.sleep(2) # put value here as seconds, 2 is 2 seconds
    • 或**
from time import sleep
sleep(60) # put value here as seconds, 60 is 60 seconds = 1 minute
    • 示例代码:**
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
    • 有关详细信息,请访问:**https://www.example.comdocs.python.org/3/library/time.html#time.sleep
yeotifhr

yeotifhr4#

    • 您可以使用代码程序:**
import time
time.sleep(2) # put value here as seconds, 2 is 2 seconds
    • 或**
from time import sleep
sleep(60) # put value here as seconds, 60 is 60 seconds = 1 minute
    • 示例代码:**
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
    • 示例代码2:**
import time
def function1():
    print('function1 is sleeping for 2 seconds...')
    time.sleep(2)

for i in range(10): 
    function1()
    • 示例代码3:**
import time
for i in range(10): 
    if i%2==0:
        print('{} is even number...'.format(i))
        time.sleep(2)
    else:
        print('{} is odd number...'.format(i))
        time.sleep(2)
    • 有关详细信息,请访问:**https://www.example.comdocs.python.org/3/library/time.html#time.sleep

相关问题