EM::Channel#subscribe behavior

21 views
Skip to first unread message

Arindam Mukherjee

unread,
Jul 22, 2016, 4:00:40 AM7/22/16
to EventMachine
I have a main thread and a separate EM thread. I am trying to push a message from the EM thread that can be read on the main thread. Here is the code:

    require "rubygems"
    require "eventmachine"
       
    t = Thread.new {
      p "EM thread: #{Thread.current}"
      EM.run
    }

    # Set up channel and queue
    q = EM::Queue.new
    ch = EM::Channel.new
   
    # Define pop action for queue
    q.pop do |msg|
      EM.add_timer(2) do      # Runs in the event loop
        ch.push msg.upcase
      end
    end
   
    # Subscribe to channel
    sid = ch.subscribe do |resp|
      p "Callback thread: #{Thread.current}"    # Runs in the event thread
      puts "Response recvd: #{resp}"
    end
   
    p "Main thread: #{Thread.current}"
   
    # push task to queue
    q.push "hello"
   
    puts "Waiting for 5 secs"
    sleep 5
   
    EM.stop

The ch.subscribe callback, runs in the event thread. Is there a way for a callback to be run in the context of the main thread when the channel has some message?
Reply all
Reply to author
Forward
0 new messages