0

I have a thread doing things in background and I want to suspend it whenever my program has a real thing to do. Once that is finished I want the background thread to continue. E.g.

ta = Thread.new { loop { print 'a'; sleep 0.2 } }

sleep 0.5

# put ta to sleep
5.times { print 'b'; sleep 0.2 }
# let ta resume

sleep 0.8
puts

The output should be something like aaabbbbbaaaaa. Currently it is aaabababababaaaaa.

Although a thread can stop itself through Thread.stop, I found no method to stop a thread from "outside". Is there a simple solution?

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
  • 1
    I did some research and I haven't found anything in the `Thread` class (which you did yourself, I assume). From `#ruby`: JonnieCache: you need a system of locks/semaphores/etc. prepare for pain. https://github.com/igrigorik/agent – Reactormonk Dec 02 '11 at 12:50

1 Answers1

2

What you need is a Mutex:

$my_mutex = Mutex.new

t1 = Thread.new do
  loop do
    $my_mutex.synchronize do
      print 'a'
    end
    sleep 0.2
  end
end

sleep 0.5

$my_mutex.synchronize do
  5.times do
    print 'b'
    sleep 0.2
  end
end

sleep 0.8

puts
sleep

Output:

aaabbbbbaaaaa
aaaaaaaaaaaaaaaaa...
Guilherme Bernal
  • 8,183
  • 25
  • 43
  • Thank you, this will work. But a restriction is that the thread to be stopped has to be cooperative and release/reclaim the mutex regularily. I was hoping for something to enforce stopping. – undur_gongor Dec 02 '11 at 16:13