python - 具有Autobahn,ApplicationRunner和ApplicationSession的多线程

标签 python multithreading python-3.x twisted

python-running-autobahnpython-asyncio-websocket-server-in-a-separate-subproce

can-an-asyncio-event-loop-run-in-the-background-without-suspending-the-python-in

试图通过上面的两个链接来解决我的问题,但我没有。

我有以下错误: RuntimeError:线程“Thread-1”中没有当前事件循环。

这里的代码示例(python 3):

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import time
import threading


class PoloniexWebsocket(ApplicationSession):

    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):

        def on_ticker(*args):
            print(args)

        try:
            yield from self.subscribe(on_ticker, 'ticker')

        except Exception as e:
            print("Could not subscribe to topic:", e)


def poloniex_worker():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)


def other_worker():
    while True:
        print('Thank you')
        time.sleep(2)


if __name__ == "__main__":
    polo_worker = threading.Thread(None, poloniex_worker, None, (), {})
    thank_worker = threading.Thread(None, other_worker, None, (), {})

    polo_worker.start()
    thank_worker.start()

    polo_worker.join()
    thank_worker.join()

因此,我的最终目标是在开始时启动2个线程。只有一个需要使用ApplicationSession和ApplicationRunner。谢谢你。

最佳答案

一个单独的线程必须具有自己的事件循环。因此,如果poloniex_worker需要监听一个websocket,则需要它自己的事件循环:

def poloniex_worker():
    asyncio.set_event_loop(asyncio.new_event_loop())
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)

但是,如果您使用的是Unix计算机,则尝试执行此操作将遇到另一个错误。高速公路异步使用Unix信号,但是这些Unix信号仅在主线程中工作。如果您不打算使用Unix信号,则可以将其关闭。为此,您必须转到定义ApplicationRunner的文件。那是我机器上python3.5> site-packages> autobahn> asyncio中的wamp.py。您可以将代码的信号处理部分注释掉,如下所示:
# try:
#     loop.add_signal_handler(signal.SIGTERM, loop.stop)
# except NotImplementedError:
#     # signals are not available on Windows
#     pass

这一切都是很多工作。如果您不是绝对需要在与主线程不同的线程中运行ApplicationSession,最好在主线程中运行ApplicationSession。

关于python - 具有Autobahn,ApplicationRunner和ApplicationSession的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38298548/

相关文章:

python - 使用 Flask-SQLAlchemy 连接到 MSSQL 数据库

python - 简单的 pandas MultiIndex 切片

java 使用Executor实现多线程

python-3.x - 在不使用 fit 方法中的回调的情况下在 Tensorboard 中显示 Keras 图形

python-3.x - 新命令中断循环

python - 在python中,如果一个函数没有return语句,它会返回什么?

python - 使用 Ray 进行基本集群计算和数据管理

python - 'OneToOneField' 的实例没有 'username' 成员

java - ScheduledFuture.cancel() 方法的同步

c++ - 当指向对象的指针作为参数传递给 std::thread 时的内存可见性