4

我想知道是否可以停止执行已延迟的操作。

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

这是一个示例 Web 套接字服务器。有时当我收到一条消息我想做一些 IO 时,稍后可能会有另一条消息进来,需要读取相同的内容,下一个内容总是优先于上一个内容。所以我想取消第一个操作并执行第二个操作。

4

1 回答 1

1

这是我的解决方案。它类似于 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
于 2013-10-04T18:11:15.287 回答