在gevent处理线程/绿灯杀死

时间:2016-02-07 23:39:53

标签: python multithreading gevent

我希望在gevent中创建一个非阻塞线程/ Greenlit。该线程应该运行,直到发送某种信号来停止它,此时我希望执行一个动作(保存一些数据)。

从gevent kill docs我希望以下代码在被杀后打印Done

import gevent
def myloop():
    try:
        while True:
            pass
    except gevent.greenlet.GreenletExit:
        print "Done"
thread = gevent.spawn(myloop)
thread.kill()

但是,这不会发生。任何想法为什么?我做错了什么吗?如何实现指定的行为?

1 个答案:

答案 0 :(得分:2)

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 private void deleteRowsBtn_Click(object sender, EventArgs e) { foreach (DataGridViewRow item in this.bSRecordsDataGridView.SelectedRows) { bSRecordsDataGridView.Rows.RemoveAt(item.Index); } db.SaveChanges(); } in your while loop, sleep(0) will raise GreenletExit and the loop will break.

In fact, you can deduce this by looking at your code :

sleep

There is syntaxically nothing that can raise an exception here. We need to do something that can raise, and that's try: while True: pass except ...: ... .