使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