Reputation: 2707
I know that I can block the current thread with time.sleep(0xFFFFFFFFF) but is there other way?
I know that this may be seem silly, but there are use cases.
For example this could be used inside a try
except
to catch KeyboardInterrupt
exception.
See this: https://stackoverflow.com/a/69744286/1951448
Or if there are daemonic threads running and there is nothing more to do, but don't want the threads be killed, then the main thread has to be suspended.
To clarify, I dont want to kill the thread, I want to suspend it.
Upvotes: 1
Views: 1512
Reputation: 73081
It's unusual to want to block a thread indefinitely, so AFAIK there isn't an API designed specifically for that use case.
The simplest way to achieve that goal would be to call time.sleep()
with a large value, as you suggested; wrap it in a while True:
loop so that even if the specified time-period expires, your thread will wake up and then go immediately back to sleep again.
OTOH if for some reason you want to guarantee that your thread never wakes up at all, no matter how much time passes, you could have it call recv()
on a socket that you are certain will never actually receive any data, e.g.:
import socket
print("About to sleep forever")
[sockA, sockB] = socket.socketpair()
junk = sockA.recv(1) # will never return since sockA will never receive any data
print("This should never get printed")
Upvotes: 1