Skip to content

Instantly share code, notes, and snippets.

@shikhalev
Created February 24, 2014 22:25
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 shikhalev/9198544 to your computer and use it in GitHub Desktop.
Save shikhalev/9198544 to your computer and use it in GitHub Desktop.
Примеры к статье «Ruby и многозадачность»
# encoding: utf-8
puts 'begin'
th = Thread.new do
(1..3).each { |i| puts i }
end
# sleep 0
puts '---'
th.join
puts 'end'
# encoding: utf-8
th = Thread.new do
puts 'started'
Thread.stop
puts 'continued'
sleep 100
puts 'finished'
end
sleep 0.1
puts 'wakeup'
th.wakeup
sleep 0
puts 'terminate'
th.terminate
th.join
# encoding: utf-8
flag = true
5.times do
Thread.new do
puts 'true' if flag
flag = false
end
end
Thread.list.each do |th|
if th != Thread.current
th.join
end
end
# encoding: utf-8
flag = true
5.times do
Thread.new do
Thread.exclusive do
puts 'true' if flag
flag = false
end
end
end
Thread.list.each do |th|
if th != Thread.current
th.join
end
end
# encoding: utf-8
alpha = true
alpha_m = Mutex.new
beta = true
beta_m = Mutex.new
5.times do
Thread.new do
alpha_m.synchronize do
puts 'alpha' if alpha
alpha = false
end
beta_m.synchronize do
puts 'beta' if beta
beta = false
end
end
end
Thread.list.each do |th|
if th != Thread.current
th.join
end
end
# encoding: utf-8
th = Thread.new do
sleep 0.1
p Thread.current.thread_variable_get 'alpha'
end
th.thread_variable_set 'alpha', :alpha
th.join
# encoding: utf-8
th = Thread.new do
sleep 0.1
p Thread.current['alpha']
end
th['alpha'] = :alpha
th.join
# encoding: utf-8
f = Fiber.new do
current = Time.new
loop do
last = current
current = Time.new
Fiber.yield [last, current]
end
end
5.times do
p f.resume
sleep 1
end
# encoding: utf-8
pid = fork do
3.times do |i|
sleep 0.01
puts "Child [#{Process.pid}]: #{i}"
end
end
3.times do |i|
sleep 0.01
puts "Parent [#{Process.pid}]: #{i}"
end
Process.waitpid pid
# encoding: utf-8
child = fork do
count = 0
Signal.trap :USR1 do
count += 1
puts "Signal USR1: #{count}"
end
Signal.trap :TERM do
puts 'Signal TERM'
exit
end
sleep 1000
puts 'Ooops!'
end
Signal.trap :CHLD do
puts 'Child died.'
end
Process.kill :USR1, child
sleep 0.01
#Process.kill :USR2, child
Process.kill :USR1, child
Process.kill :TERM, child
Process.wait
# encoding: utf-8
rd, wr = IO.pipe
child = fork do
rd.close
wr.write 'From Child'
wr.close
end
wr.close
msg = rd.read
rd.close
p msg
Process.wait
# encoding: utf-8
rd, wr = IO.pipe
child = spawn "echo 'External Child'",
[ STDERR, STDOUT ] => wr
wr.close
msg = rd.read
rd.close
p msg
Process.wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment