以下のようにサーバーで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
。これを行う 1 つの方法は、次のように操作を新しいスレッド内に配置すること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
しかし、イベントが発生するたびに新しいスレッドを作成すると、重いようで、応答が遅くなります。したがって、1 つのスレッドを で処理されるすべてのイベントで共有し、別のスレッドを で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
これを行うにはどうすればよいでしょうか。または、相互にブロックしない方法で websocketonmessage
イベントに応答するためのより良い構造はありますか?