Reputation: 1394
I wish to create a non-blocking thread/Greenlit in gevent. The thread is meant to run until some kind of signal is sent to stop it, at which point I wish to perform an action (save some data).
From the gevent kill docs I would expect the following code to print Done
upon being killed:
import gevent
def myloop():
try:
while True:
pass
except gevent.greenlet.GreenletExit:
print "Done"
thread = gevent.spawn(myloop)
thread.kill()
However, that doesn't happen. Any ideas as to why? Am I doing something horribly wrong? How can I achieve the specified behaviour?
Upvotes: 0
Views: 1857
Reputation: 6233
As your greenlet is never actually "blocking", but consuming CPU forever, it's never killed. From gevent's point of view, it's going to be killed, but this will never happen because the greenlet will never leave its while-loop.
I'm pretty sure that if you add sleep(0)
in your while loop, sleep
will raise GreenletExit and the loop will break.
In fact, you can deduce this by looking at your code :
try:
while True:
pass
except ...:
...
There is syntaxically nothing that can raise an exception here. We need to do something that can raise, and that's sleep(0)
.
Upvotes: 2