Skip to main content
 首页 » 编程设计

python之扭曲的调用远程

2024年10月24日8langtianya

我必须进行可能需要很长时间(超过 60 秒)的远程调用。我们的整个代码依赖于处理来自 callRemote 的返回值,所以这非常糟糕,因为尽管使用 twqisted + 50 个工作线程在运行,但我们一直阻塞在 IO 上。

我们目前使用类似的东西

result = threads.blockingCallFromThread(reactor, callRemote, "method", args) 

并获取结果/继续,但正如其名称所示,它会阻塞事件循环,因此我们不能同时等待多个结果。

我无法重构整个代码以使其异步,因此我认为唯一的方法是将长 IO 任务推迟到线程。

我试图在线程中进行远程调用,但我找不到从阻塞调用中获取结果的方法。进行了远程调用,结果在某处,但我无法了解它。

我目前正在尝试做的事情看起来像

reactor.callInThread(callRemote, name, *args, **kw) 

它返回一个空的 Deferred(为什么?)。

我试图将结果放入某种队列中,但它行不通。我该怎么做?

请您参考如下方法:

据我所知,blockingCallFromThread 在reactor 的线程中执行代码。这就是为什么它不能按您的需要工作。

如果我理解正确的话,您需要将一些操作移出 reactor 的线程,并将结果放入 reactor 的线程。

对于相同的情况,我使用 deferToThread 方法。 延迟示例:

import time 
from twisted.internet import reactor, threads 
 
def doLongCalculation(): 
    time.sleep(1) 
    return 3 
 
def printResult(x): 
    print x 
 
# run method in thread and get result as defer.Deferred 
d = threads.deferToThread(doLongCalculation) 
d.addCallback(printResult) 
reactor.run() 

此外,您可能对 threads.deferToThreadPool 感兴趣。

Documentation about threading in Twisted.