fork-threads.rb
| 1 |
#!/usr/bin/ruby
|
|---|---|
| 2 |
# This program creates some threads, forks, and then
|
| 3 |
# sees how many threads are in the child and parent.
|
| 4 |
|
| 5 |
require 'sync'
|
| 6 |
|
| 7 |
class Checker |
| 8 |
attr_accessor :sync, :threads |
| 9 |
def initialize() |
| 10 |
@threads = []
|
| 11 |
@sync = Sync.new |
| 12 |
end
|
| 13 |
|
| 14 |
def run |
| 15 |
(1..10).to_a.each do |i| |
| 16 |
@threads << Thread.new(i) do |j| |
| 17 |
print "PRE th[#{j}] sees #{Thread.list.length} threads\n"
|
| 18 |
sync.synchronize do
|
| 19 |
pid = fork do
|
| 20 |
sleep 3
|
| 21 |
print "inside #{j}'s child process\n"
|
| 22 |
# sync.synchronize do
|
| 23 |
IO.popen("cat > /dev/null", "w") do |p| |
| 24 |
p.puts j |
| 25 |
end
|
| 26 |
# end
|
| 27 |
end
|
| 28 |
Process.wait(pid)
|
| 29 |
print "POST th[#{j}] sees #{Thread.list.length} threads\n"
|
| 30 |
end
|
| 31 |
end
|
| 32 |
end
|
| 33 |
|
| 34 |
@threads.each {|th| th.join}
|
| 35 |
end
|
| 36 |
end
|
| 37 |
|
| 38 |
c = Checker.new
|
| 39 |
c.run |