Time.sleep is thread sleep? Process sleep?

Asked 1 years ago, Updated 1 years ago, 138 views

time from Linux/UNIX to Python.Does sleep() block only one thread? Or do you block the entire process?

multithreading python time sleep python-internals

2022-09-22 15:30

1 Answers

time.I hope it's written in sleep

Suspend execution of the calling thread for the given number of seconds.

That's what it says. Only the thread is blocked Maybe it's true, but if you experiment with it,

# coding=utf-8
import thread, time, datetime

def counter(id, timeToSleep):
    print "thread %d entry. sleep as much as %s" %(id, timeToSleep)
    time.sleep(timeToSleep)
    print "thread %d, current time:%s" %(id, datetime.datetime.now().time())

print "Start time :", datetime.datetime.now().time()
thread.start_new_thread(counter, (0, 10,))
thread.start_new_thread(counter, (1, 10,))

time.sleep(20) #Wait until the thread is finished

Result:

 Start time: 16:19:51.790819
Entering Thread 0. Sleep as much as 10
Thread 1 entry. Sleep as much as 10
Thread 0, Current time: 16:20:01.793599
Thread 1, Current Time: 16:20:01.793714

You can see that each thread sleeps only for as long as it sleeps.


2022-09-22 15:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.