time.sleep -- 休眠线程还是进程? [英] time.sleep -- sleeps thread or process?
问题描述
在 Python for *nix 中,time.sleep()
是阻塞线程还是进程?
它阻塞了线程.如果您查看 Python 源代码中的 Modules/timemodule.c,您会看到在对 floatsleep()
的调用中,睡眠操作的实质部分包含在 Py_BEGIN_ALLOW_THREADS 和 Py_END_ALLOW_THREADS 块中,允许其他线程在当前线程休眠时继续执行.你也可以用一个简单的 python 程序来测试:
导入时间从线程导入线程班级工作者(线程):定义运行(自我):对于 x 范围内的 x(0,11):打印 x时间.sleep(1)班级服务员(线程):定义运行(自我):对于 x 范围内的 x(100,103):打印 x时间.sleep(5)定义运行():工人().开始()服务员().开始()
将打印的内容:
<预><代码>>>>thread_test.run()0100>>>12345101678910102In Python for *nix, does time.sleep()
block the thread or the process?
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()
Which will print:
>>> thread_test.run()
0
100
>>> 1
2
3
4
5
101
6
7
8
9
10
102
这篇关于time.sleep -- 休眠线程还是进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!