Riddle
Riddle

Reputation: 89

Ruby execution getting stuck in a single thread

I am trying to listen on a socket while performing other tasks but my program just gets stuck in the listening loop and can't do anything else. The code I'm using is:

t = Thread.new do
  @listener.listen
end
t.join

puts('do more stuff')

Where @listener.listen is:

def listen

  puts('listening')
  while true
    data = p @socket.recv(1000)      # Receive
    respond(JSON.parse(data))
  end
end

If I do this the program gets stuck in the while loop and "do more stuff" is never printed. Anyone know why this might be happening?

Upvotes: 0

Views: 645

Answers (2)

BroiSatse
BroiSatse

Reputation: 44685

You don't want to call join. join waits for its thread to finish.

Upvotes: 1

CuriousMind
CuriousMind

Reputation: 34145

Threads are not a good fit. Basically, what you need is a loop which sets a callback on a new task and moves to the next task. You might want to check the event-loop approach using EventMachine.

Try setting abort_on_exception to check for exceptions and a timeout in seconds:

Thread.abort_on_exception = true
t = Thread.new do
  @listener.listen
end
t.join(5) #Does not return until all threads exit or 5 sec(timeout) have passed.

Also, in listen?:

def listen

  puts('listening')
  while true
    data = p @socket.recv(1000)      # Receive
    respond(JSON.parse(data))
  end
end

You have a infinite loop while true. Do you check to see if it ever returns false?

def listen

  puts('listening')
  loop do
    data = p @socket.recv(1000)      # Receive
    result = respond(JSON.parse(data))
    if result
      puts "Still True."
    else
      puts "Got False. Exiting loop.."
      break
    end
  end
  result
end

Hope it helps.

Upvotes: 1

Related Questions