Skip to content

Instantly share code, notes, and snippets.

@ileitch
Created June 11, 2014 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ileitch/b8d9d780075765a8c9a1 to your computer and use it in GitHub Desktop.
Save ileitch/b8d9d780075765a8c9a1 to your computer and use it in GitHub Desktop.
require 'monitor'
obj = Object.new
obj.extend(MonitorMixin)
condition = obj.new_cond
duration = 4
class Signaler
def initialize(duration, obj, condition)
@duration = duration
@obj = obj
@condition = condition
@stop = false
end
def start
@t = Thread.new do
loop do
break if @stop
sleep @duration
signal
end
end
end
def signal
@obj.synchronize do
@condition.signal
end
end
def stop
@stop = true
signal
@t.join
end
end
class Worker
def initialize(duration, obj, condition, signaler)
@duration = duration
@obj = obj
@condition = condition
@signaler = signaler
@stop = false
end
def work
@t = Thread.new do
loop do
puts 'working...'
sleep 0.2
puts 'done'
@obj.synchronize do
puts 'waiting...'
@condition.wait(100000)
end
break if @stop
end
puts 'Stopped'
end
end
def stop
puts 'Stopping...'
@stop = true
@signaler.stop
end
def wait
@t.join
end
end
s = Signaler.new(duration, obj, condition)
s.start
w = Worker.new(duration, obj, condition, s)
w.work
read_io, write_io = IO.pipe
Thread.new do
loop do
read_io.read(1)
w.stop
end
end
Signal.trap('INT') do
write_io.write(1)
end
w.wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment