问题:time.sleep —休眠线程或进程?

在Python for * nix中,是否time.sleep()阻塞线程或进程?

In Python for *nix, does time.sleep() block the thread or the process?


回答 0

它阻塞线程。如果在Python源代码中查看Modules / timemodule.c,您会看到在调用中floatsleep(),睡眠操作的实质部分包装在Py_BEGIN_ALLOW_THREADS和Py_END_ALLOW_THREADS块中,从而允许其他线程在当前线程继续执行一睡觉。您也可以使用简单的python程序进行测试:

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

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

回答 1

它只会休眠线程,除非您的应用程序只有一个线程,在这种情况下,它将休眠线程并有效地进程。

睡眠中的python文档未指定此内容,因此我当然可以理解混淆!

http://docs.python.org/2/library/time.html

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!

http://docs.python.org/2/library/time.html


回答 2

只是线程。


回答 3

该线程将阻塞,但是该进程仍然有效。

在单线程应用程序中,这意味着您在睡眠时一切都被阻止了。在多线程应用程序中,只有您显式“睡眠”的线程将被阻塞,其他线程仍在进程中运行。

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.


回答 4

只有线程,除非您的进程具有单个线程。

Only the thread unless your process has a single thread.


回答 5

进程本身无法运行。关于执行,进程只是线程的容器。这意味着您根本无法暂停该过程。它根本不适用于过程。

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.


回答 6

如果它在同一线程中执行,则它将阻塞一个线程,如果不是从主代码中执行,则它将阻塞该线程

it blocks a thread if it is executed in the same thread not if it is executed from the main code


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。