我在服务器上使用 websocket,如下所示。它响应onmessage
事件,并根据消息进行不同的任务:
require "websocket-eventmachine-server"
WebSocket::EventMachine::Server.start(host: some_server_name, port: some_port) do |ws|
# (A) Here, the current thread is the main thread
ws.onmessage do |s|
if foo
# (B) Here, the current thread is the main thread
...
else
# (C) Here, the current thread is the main thread
...
end
end
end
每次执行每个onmessage
事件的线程(如上所述)都是相同的,并且它们与主线程相同(B
如上所述)。C
A
我想B
在一个单独的线程中执行代码作为C
. 一种方法是将操作放入新线程中,如下所示B
:C
WebSocket::EventMachine::Server.start(host: some_server_name, port: some_port) do |ws|
# (A) Here, the current thread is the main thread
ws.onmessage do |s|
if foo
# (B) Here, the current thread will be created each time.
Thread.new{...}
else
# (C) Here, the current thread will be created each time.
Thread.new{...}
end
end
end
但是每次发生事件时创建一个新线程似乎很重,并且使响应变慢。因此,我希望在 中处理的所有事件之间共享一个线程onmessage
,B
并在中处理的所有事件之间共享另一个线程C
:
WebSocket::EventMachine::Server.start(host: some_server_name, port: some_port) do |ws|
# (A) Here, the current thread is the main thread
ws.onmessage do |s|
if foo
# (B) I want this part to be executed in a thread
# that does not change each time, but is different from the thread in C
...
else
# (C) I want this part to be executed in a thread
# that does not change each time, but is different from the thread in B
...
end
end
end
什么是这样做的好方法?或者,是否有更好的结构以onmessage
相互非阻塞的方式响应 websocket 事件?