Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time.sleep -- sleeps thread or process?

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

like image 705
Jeremy Dunck Avatar asked Sep 18 '08 14:09

Jeremy Dunck


People also ask

Does time sleep stop threads?

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

What does time sleep do in Python?

Python time sleep() Method Python time method sleep() suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.

Does time sleep release Gil?

Model #3: Non-Python code can explicitly release the GILIf we run time. sleep(3) , that will do nothing for 3 seconds. We saw above that long-running extension code can prevent the GIL from being automatically switched between threads.

What's thread sleep () in threading?

Suspends the current thread for the specified number of milliseconds. Suspends the current thread for the specified amount of time.


3 Answers

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
like image 198
Nick Bastin Avatar answered Oct 18 '22 04:10

Nick Bastin


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!

like image 25
Zach Burlingame Avatar answered Oct 18 '22 05:10

Zach Burlingame


Just the thread.

like image 39
finnw Avatar answered Oct 18 '22 04:10

finnw