time.sleep — sleeps thread or process?

2019-01-05 08:17发布

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

6条回答
走好不送
2楼-- · 2019-01-05 08:34

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.

查看更多
迷人小祖宗
3楼-- · 2019-01-05 08:35

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
查看更多
看我几分像从前
4楼-- · 2019-01-05 08:49

Only the thread unless your process has a single thread.

查看更多
可以哭但决不认输i
5楼-- · 2019-01-05 08:51

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

查看更多
孤傲高冷的网名
6楼-- · 2019-01-05 08:51

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.

查看更多
我想做一个坏孩纸
7楼-- · 2019-01-05 08:53

Just the thread.

查看更多
登录 后发表回答