python线程之间的互相调用_如何在python中的线程之间传递异常

I need to pass exceptions across a thread boundary.

I'm using python embedded in a non thread safe app which has one thread safe call, post_event(callable), which calls callable from its main thread.

I am running a pygtk gui in a seperate thread, so when a button is clicked I post an event with post_event, and wait for it to finish before continuing. But I need the caller to know if the callee threw an exception, and raise it if so. I'm not too worried about the traceback, just the exception itself.

My code is roughly:

class Callback():

def __init__(self,func,*args):

self.func=func

self.args=args

self.event=threading.Event()

self.result=None

self.exception=None

def __call__(self):

gtk.gdk.threads_enter()

try:

self.result=self.func(*self.args)

except:

#what do I do here? How do I store the exception?

pass

finally:

gtk.gdk.threads_leave()

self.event.set()

def post(self):

post_event(self)

gtk.gdk.threads_leave()

self.event.wait()

gtk.gdk.threads_enter()

if self.exception:

raise self.exception

return self.result

Any help appreciated, thanks.

解决方案#what do I do here? How do I store the exception?

Use sys.exc_info()[:2], see this wiki

Best way to communicate among threads is Queue. Have the main thread instantiate a Queue.Queue instance and pass it to subthreads; when a subthread has something to communicate back to the master it uses .put on that queue (e.g. a tuple with thread id, exception type, exception value -- or, other useful info, not necessarily exception-related, just make sure the first item of a tuple identifies the kind of info;-). The master can .get those info-units back when it wants, with various choices for synchronization and so on.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值