Created
June 11, 2014 22:57
-
-
Save ileitch/b8d9d780075765a8c9a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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