【问题标题】:How to run twisted in its own thread and stop properly?如何在自己的线程中运行并正确停止?
【发布时间】:2015-10-28 17:33:42
【问题描述】:

我在我的应用程序中使用了 twisted 并在它自己的线程中运行它。像这样使用 twisted 效果很好,但它永远不会正确停止。

例子:

# Python 2.7.6
# Twisted==15.4.0

import time
import threading
from twisted.internet import reactor

print("starting reactor")
reactor_thread = threading.Thread(target=reactor.run,
                              kwargs={"installSignalHandlers": False})
reactor_thread.start()
print("reactor started")

time.sleep(1)

print("stopping reactor")
reactor.stop()
print("joining thread")
reactor_thread.join()
print("reactor stopped")  # <- never reached

输出:

starting reactor
reactor started
stopping reactor
joining thread

【问题讨论】:

    标签: python multithreading twisted


    【解决方案1】:

    您应该使用Crochet。它为您在线程中运行反应器。

    您还应该认真考虑重构您的应用程序以尊重 Twisted 的习惯用法。这样做将允许您的应用程序与其他 Twisted 应用程序组合并减轻您的维护负担。 (这样你就不必在线程中运行反应器了。)

    【讨论】:

    • 完全重构我的应用程序并不是一个真正的选择,因为我依赖于也必须更改的依赖项。我要做的就是可靠地停止反应堆。
    猜你喜欢
    • 1970-01-01
    • 2019-08-09
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多