我想知道是否可以停止执行已推迟的操作。
require 'rubygems'
require 'em-websocket'
EM.run do
EM::WebSocket.start(:host => '0.0.0.0', :port => 8080) do |ws|
ws.onmessage do |msg|
op = proc do
sleep 5 # Thread safe IO here that is safely killed
true
end
callback = proc do |result|
puts "Done!"
end
EM.defer(op, callback)
end
end
end
这是一个示例网络套接字服务器。有时,当我收到一条消息时,我想做一些 IO,稍后可能会收到另一条消息,需要读取相同的内容,下一个总是优先于前一个。所以我想取消第一个操作并执行第二个操作。
最佳答案
这是我的解决方案。它类似于 EM.queue 解决方案,但只是使用哈希。
require 'rubygems'
require 'em-websocket'
require 'json'
EM.run do
EM::WebSocket.start(:host => '0.0.0.0', :port => 3333) do |ws|
mutex = Mutex.new # to make thread safe. See https://github.com/eventmachine/eventmachine/blob/master/lib/eventmachine.rb#L981
queue = EM::Queue.new
ws.onmessage do |msg|
message_type = JSON.parse(msg)["type"]
op = proc do
mutex.synchronize do
if message_type == "preferred"
puts "killing non preferred\n"
queue.size.times { queue.pop {|thread| thread.kill } }
end
queue << Thread.current
end
puts "doing the long running process"
sleep 15 # Thread safe IO here that is safely killed
true
end
callback = proc do |result|
puts "Finished #{message_type} #{msg}"
end
EM.defer(op, callback)
end
end
end
关于Ruby Event Machine 停止或终止延迟操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19172707/