加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby Event Machine停止或终止deffered操作

发布时间:2020-12-17 02:05:21 所属栏目:百科 来源:网络整理
导读:我想知道我是否可以停止执行已被修改的操作. 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
我想知道我是否可以停止执行已被修改的操作.

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,之后可能会出现另一条需要读取相同内容的消息,接下来的事情总是优先于之前的事情.所以我想取消第一个操作并完成第二个操作.

解决方法

这是我的解决方案.它类似于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 preferredn"
            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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读