我们如何锁定已被多个 ruby 进程共享的 IO?
考虑这个脚本:
#!/usr/bin/ruby -w
# vim: ts=2 sw=2 et
if ARGV.length != 2
$stderr.puts "Usage: test-io-fork.rb num_child num_iteration"
exit 1
end
CHILD = ARGV[0].to_i
ITERATION = ARGV[1].to_i
def now
t = Time.now
"#{t.strftime('%H:%M:%S')}.#{t.usec}"
end
MAP = %w(nol satu dua tiga empat lima enam tujuh delapan sembilan)
IO.popen('-', 'w') {|pipe|
unless pipe
# Logger child
File.open('test-io-fork.log', 'w') {|log|
log.puts "#{now} Program start"
$stdin.each {|line|
log.puts "#{now} #{line}"
}
log.puts "#{now} Program end"
}
exit!
end
pipe.sync = true
pipe.puts "Before fork"
CHILD.times {|c|
fork {
pid = Process.pid
srand
ITERATION.times {|i|
n = rand(9)
sleep(n / 100000.0)
pipe.puts "##{c}:#{i} #{MAP[n]} => #{n}, #{n} => #{MAP[n]} ##{c}:#{i}"
}
}
}
}
并尝试这样:
./test-io-fork.rb 200 50
正如预期的那样,test-io-fork.log 文件将包含 IO 竞争条件的迹象。
我想要实现的是为自定义 GPS 协议制作一个 TCP 服务器,它将 GPS 点保存到数据库中。因为该服务器将处理 1000 个并发客户端,所以我想将数据库连接限制为只有一个孩子,而不是同时打开 1000 个数据库连接。该服务器将在 linux 上运行。