Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby事件机停止或终止不同的操作_Ruby_Eventmachine - Fatal编程技术网

Ruby事件机停止或终止不同的操作

Ruby事件机停止或终止不同的操作,ruby,eventmachine,Ruby,Eventmachine,我想知道我是否可以停止执行一个被取消的操作 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 kil

我想知道我是否可以停止执行一个被取消的操作

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 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
需要“rubygems”
需要“他们是websocket”
需要“json”
嗯,跑吧
EM::WebSocket.start(:host=>'0.0.0',:port=>3333)do | ws|
mutex=mutex.new#使线程安全。看见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.do
如果消息类型==“首选”
放置“清除非首选项\n”
queue.size.times{queue.pop{| thread | thread.kill}
结束

有效地排队,在任何给定的点上你不是只使用一个线程(除了反应器线程)吗?我想我得到了你想要的答案(顺便说一句,它是有效的)。但我不知道它是否有任何不必要的副作用:/这是我的解决方案:问题不清楚我为什么要这么做。是的,在这个例子中,我在任何给定的点上只使用一个线程。我的现实世界的例子是,我有两种类型的消息。类型1执行长时间运行的IO,类型2执行各种操作。当一个类型1消息传入时,它会延迟并花费很长时间,这意味着当多个类型2消息传入时,执行它们的操作和回调。我基本上只希望有一个1型操作在任何时候都进行,而不干扰任何2型操作。你不需要添加互斥体吗?我尝试过很多次,每次都有效。这里的文档似乎与您的意见一致,因此我在回答中提出了您的一些建议。应该在stack上而不是github上发布,这样你就可以得到积分了!