【发布时间】:2014-02-18 21:04:57
【问题描述】:
有很多关于 Python 和异步编码技术的教程等,但我很难过滤结果以找到我需要的东西。我是 Python 新手,所以这无济于事。
设置
我目前有两个看起来像这样的对象(请原谅我的 python 格式):
class Alphabet(parent):
def init(self, item):
self.item = item
def style_alphabet(callback):
# this method presumably takes a very long time, and fills out some properties
# of the Alphabet object
callback()
class myobj(another_parent):
def init(self):
self.alphabets = []
refresh()
def foo(self):
for item in ['a', 'b', 'c']:
letters = new Alphabet(item)
self.alphabets.append(letters)
self.screen_refresh()
for item in self.alphabets
# this is the code that I want to run asynchronously. Typically, my efforts
# all involve passing item.style_alphabet to the async object / method
# and either calling start() here or in Alphabet
item.style_alphabet(self.screen_refresh)
def refresh(self):
foo()
# redraw screen, using the refreshed alphabets
redraw_screen()
def screen_refresh(self):
# a lighter version of refresh()
redraw_screen()
这个想法是,主线程最初用不完整的Alphabet 对象绘制屏幕,填充字母对象,完成后更新屏幕。
我尝试了许多 threading.Tread、Queue.Queue 甚至期货的实现,但由于某种原因,它们要么没有工作,要么阻塞了主线程。这样就不会发生初始抽签。
我尝试过的一些异步方法:
class Async (threading.Thread):
def __init__(self, f, cb):
threading.Thread.__init__(self)
self.f = f
self.cb = cb
def run(self):
self.f()
self.cb()
def run_as_thread(f):
# When I tried this method, I assigned the callback to a property of "Alphabet"
thr = threading.Thread(target=f)
thr.start()
def run_async(f, cb):
pool = Pool(processes=1)
result = pool.apply_async(func=f, args=args, callback=cb)
【问题讨论】:
-
您能告诉我们您是如何实例化您的
Async类并调用它的start()方法(同样适用于run_as_thread())吗? -
另外,在
myobj.foo()的最后一个块中调用letters.style_alphabet()可能不是您想要的(应该是item.style_alphabet(),不是吗?)。但我猜这是某种类型的剪切和过去错误,因为这显然不是您尝试运行的实际代码。 -
Twisted 框架为您提供了您正在寻找的东西...如果您想让我具体说明...结帐 thread.deferToThread() 。它可以满足您的需求...
-
感谢您注意到字母/项目错误,Alp - 它已修复
-
Alp - Async 类和 run_as_thread() 方法已完成,这是我的问题吗?我以前从来没有做过这种事情。
标签: python python-2.7 asynchronous