time.sleep -- sleeps thread or process?

PythonMultithreadingTimeSleepPython Internals

Python Problem Overview


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

Python Solutions


Solution 1 - 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:

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

Solution 2 - Python

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!

Solution 3 - Python

Just the thread.

Solution 4 - Python

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.

Solution 5 - Python

Only the thread unless your process has a single thread.

Solution 6 - Python

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.

Solution 7 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy DunckView Question on Stackoverflow
Solution 1 - PythonNick BastinView Answer on Stackoverflow
Solution 2 - PythonZach BurlingameView Answer on Stackoverflow
Solution 3 - PythonfinnwView Answer on Stackoverflow
Solution 4 - PythonCorey GoldbergView Answer on Stackoverflow
Solution 5 - PythonAli AbbasinasabView Answer on Stackoverflow
Solution 6 - PythonDenis The MenaceView Answer on Stackoverflow
Solution 7 - Pythonuser12747367View Answer on Stackoverflow