time.sleep——睡眠线程或进程?
在 Python for *nix 中,time.sleep()
是否会阻塞线程或进程?
In Python for *nix, does time.sleep()
block the thread or the process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
进程本身不能运行。 就执行而言,进程只是线程的容器。 这意味着您根本无法暂停该过程。 它根本不适用于流程。
Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can't pause the process at all. It is simply not applicable to process.
如果它在同一个线程中执行,而不是从主代码执行,它会阻塞线程
it blocks a thread if it is executed in the same thread not if it is executed from the main code
它只会休眠线程,除非您的应用程序只有一个线程,在这种情况下,它将休眠线程并有效地休眠进程。
关于
sleep()
但没有具体说明这一点,所以我当然可以理解这种混乱!It will just sleep the thread except in the case where your application has only a single thread, in which case it will sleep the thread and effectively the process as well.
The python documentation on
sleep()
doesn't specify this however, so I can certainly understand the confusion!只是线程。
Just the thread.
线程会阻塞,但进程仍然存活。
在单线程应用程序中,这意味着在您睡眠时一切都会被阻塞。 在多线程应用程序中,只有您显式“睡眠”的线程才会阻塞,而其他线程仍在进程中运行。
The thread will block, but the process is still alive.
In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.
只有线程,除非您的进程只有一个线程。
Only the thread unless your process has a single thread.
它会阻塞线程。 如果您查看 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:Which will print: