在后台线程python/pygtk中运行计算 [英] Running computation in background thread python/pygtk

查看:99
本文介绍了在后台线程python/pygtk中运行计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以在后台运行python线程,而不会在耗时的指令期间锁定其他python线程?

我正在尝试在python(pygtk)应用程序的后台线程中进行耗时的计算.我了解线程是如何工作的.问题在于,每次我在任何线程中运行昂贵的操作(例如:大图像的PIL的image.load())时,它都会阻塞所有python线程,直到该操作完成为止,即使它在单独的线程中也是如此.

那么,有没有一种方法可以在后台运行python线程而不锁定其余的python? (我不在乎他们花多长时间,只要他们不锁定我的GUI.我只是不能让我的GUI一次不响应几秒钟).使用sleep语句不起作用,因为我的问题是需要很长时间的单个命令(例如image.load()).

解决方案

由于您使用的是pygtk,您打过threads_init()吗?

对于较新的版本:

>>> from gi.repository import GObject
>>> GObject.threads_init()

对于年长的人:

>>> import gobject
>>> gobject.threads_init()

还要确保不要从线程中调用任何GUI方法,否则应用程序会以奇怪的方式损坏.解决此问题的一种简单方法是使用GObject.idle_add:

idle_add(callable,user_data = None,priority = None)->源ID 可呼叫接收(user_data)

在没有更高优先级的情况下添加一个可调用对象 事件挂起到默认主循环.

Is there a way to run a python thread in the background without locking down the rest of python during time-consuming instructions?

I'm trying to do time-consuming calculations in a background thread of a python (pygtk) application. I understand how threads work. The problem is that each time I run an expensive operation in any thread (example: PIL's image.load() for large images), it blocks all python threads until the operation is completed, even though it is in a separate thread.

So, is there a way to run a python thread in the background without locking down the rest of python? (I don't care how long they take as long as they don't lock down my GUI. I just can't have my GUI unresponsive for several seconds at a time). Using sleep statements doesn't work because my problem is with single commands that take a long time (like image.load()).

解决方案

Since you're using pygtk, did you call threads_init()?

For newer versions:

>>> from gi.repository import GObject
>>> GObject.threads_init()

And for older ones:

>>> import gobject
>>> gobject.threads_init()

Also make sure you do not call any GUI method from your thread or your application will break in weird ways. An easy way around this is to use GObject.idle_add:

idle_add(callable, user_data=None, priority=None) -> source id callable receives (user_data)

Adds a callable to be called whenever there are no higher priority events pending to the default main loop.

这篇关于在后台线程python/pygtk中运行计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆