2

Let's say I'm inside a thread:

Thread.new do
  #something
end

And let's say that "something" is not threadsafe and needs to run on the main thread.

Is there any way in Ruby to dispatch that code to be executed on the main thread?

MikeC8
  • 3,783
  • 4
  • 27
  • 33
  • 4
    Please look at http://stackoverflow.com/questions/10045693/how-to-communicate-with-threads-in-ruby and http://stackoverflow.com/questions/3208462/does-ruby-have-the-java-equivalent-of-synchronize-keyword – Wand Maker Aug 16 '15 at 07:24

1 Answers1

0

You could use a queue to send proc's to the main thread and then call them from the main thread like this:

command_queue = Queue.new

# Child thread
Thread.new do
  sleep 1

  command_queue << proc { puts "1" }

  sleep 1

  command_queue << proc { puts "2" }

  sleep 1

  command_queue << proc { exit }
end

# Main thread
while command = command_queue.pop
  command.call
end
kaspernj
  • 1,243
  • 11
  • 16