time.sleep-休眠线程或进程吗? [英] time.sleep -- sleeps thread or process?
本文介绍了time.sleep-休眠线程或进程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python for * nix中,time.sleep()
会阻塞线程或进程吗?
In Python for *nix, does time.sleep()
block the thread or the process?
推荐答案
它阻止线程.如果在Python源代码中查看Modules/timemodule.c,您会发现在对floatsleep()
的调用中,睡眠操作的实质部分包装在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块中,从而允许其他线程继续执行而当前的一个正在睡觉.您还可以使用简单的python程序对此进行测试:
It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep()
, the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program:
import time
from threading import Thread
class worker(Thread):
def run(self):
for x in xrange(0,11):
print x
time.sleep(1)
class waiter(Thread):
def run(self):
for x in xrange(100,103):
print x
time.sleep(5)
def run():
worker().start()
waiter().start()
将打印:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
这篇关于time.sleep-休眠线程或进程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文