使Tornado Websocket处理程序线程安全 [英] Making Tornado websocket handler thread safe

查看:417
本文介绍了使Tornado Websocket处理程序线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Tornado的websocket服务器处理程序从线程写入消息时,我随机收到错误1006((通过断开TCP连接使WebSocket连接失败).

I am randomly getting error 1006 ( (I failed the WebSocket connection by dropping the TCP connection) when trying to write messages from threads using Tornado's websocket server handler.

我创建了N个线程,并将ws_handler传递给它们. 但是当我开始使用

I created N threads and passed my ws_handler to them. But when I start using

self.ws_handler.write_message(jsondata)

对于大量线程,我一直收到相同的错误.

for a large number of threads, I keep getting the same error.

据我了解,1006是在websocket之间跳过心跳"通信时TCP连接断开.我猜这是由于线程并行运行并尝试发送消息.我使用2-3个线程对其进行了测试,它可以正常工作,但对于大量线程却不能.

From what I understand, 1006 is TCP connection dropped when a 'heartbeat' communication is skipped between websockets. I am guessing this is because of threads running in parallel and trying to send messages. I tested it using 2-3 threads and it works fine but for large number it doesn't.

我想知道是否有任何方法可以在线程内实现消息发送(意味着锁由ws_handler内部处理并相应地发送).

I wonder if there's any method to achieve message sending within threads.( meaning lock being handled internally by ws_handler and sending accordingly).

我正在考虑的一种解决方案是将 jsondata 推送到队列,并让另一个单线程推送消息,但我担心会造成瓶颈.

One solution I am thinking of is to push jsondata into a queue and have another single thread push the messages, but I fear that would create a bottleneck.

我的客户是AutobahnPython.

My client is AutobahnPython.

推荐答案

Tornado基于单线程事件循环.与Tornado对象的所有交互都必须在事件循环的线程上.需要将控制权转移回事件循环时,请从另一个线程使用IOLoop.current().add_callback().

Tornado is based on a single-threaded event loop; all interactions with Tornado objects must be on the event loop's thread. Use IOLoop.current().add_callback() from another thread when you need to transfer control back to the event loop.

另请参见 http://www.tornadoweb.org/zh_CN/stable/web.html#thread-safety-notes

这篇关于使Tornado Websocket处理程序线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆