python - 扭曲的调用远程

标签 python multithreading asynchronous twisted

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

我们目前使用类似的东西

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

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

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

我正在尝试在线程中进行远程调用,但我找不到从阻塞回调中获取结果的方法。进行了远程调用,结果在某个地方,但我就是无法获取它。

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

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

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

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

最佳答案

AFAIK,blockingCallFromThreadreactor 的线程中执行代码。这就是为什么它不能按您的需要工作。

如果我理解正确,您需要将一些操作从 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.

关于python - 扭曲的调用远程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37075309/

相关文章:

python - 使用没有 ID 的 Selenium 查找并单击按钮

python - 检查字典中是否存在一个项目,这是一种不好的做法吗?

web-services - 使用 JAX-WS : Use wsimport support for asynchrony or roll my own? 的异步 Web 服务调用

安卓 "Only the original thread that created a view hierarchy can touch its views."

ios - Xamarin - WCF 异步回调中的异常处理不起作用 - 应用程序崩溃

c# - 没有完成端口的异步 IO?

python - 如何减少Windows中的CPU使用率?

python - 我应该使用什么 python 模块来编辑 word 文档然后将其转换为 pdf?

java - 同时运行多个线程,然后运行主线程

Python:忽略后台进程中的信号