How to do inter-process locking with forked Ruby processes? -
objective
increment counter using ruby's fork
method , several workers
disclaimers
- i not want use external dependencies this
- usage of ruby's
thread
class not allowed - i want see if possible using
fork
here's little shared memory mock
class memory def self.address= value @value = value end def self.address @value end end
here's worker
class worker def initialize mutex @mutex = mutex end def work @mutex.synchronize print "begin: %d " % (tmp=memory.address) sleep 0.05 print "end: %d \n" % (memory.address = tmp + 1) end end end
let's run it
# init memory.address = 0 mutex = mutex.new # create workers workers = [] 10.times workers << fork worker.new(mutex).work end end # wait workers finish process.waitall
output
begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 begin: 0 end: 1 end: 1 end: 1 end: 1 end: 1 end: 1 end: 1 end: 1 end: 1 end: 1
expected output
begin: 0 end: 1 begin: 1 end: 2 begin: 2 end: 3 begin: 3 end: 4 begin: 4 end: 5 begin: 5 end: 6 begin: 6 end: 7 begin: 7 end: 8 begin: 8 end: 9 begin: 9 end: 10
side questions:
- am supposed using single mutex?
- does matter if each worker creates own mutex?
forked processes inherit parent's resources memory copy (or copy on write): changes made in 1 process have no effect on other ones.
similarly each process has own copy of mutex, calls synchronise don't achieve anything.
if need communicate child processes, 1 way use pipe (see docs io). each process inherits copy of pipe , writes 1 process show in other process.
child_in, parent_out = io.pipe parent_in, child_out = io.pipe process.fork parent_out.close parent_in.close #data written child_out appears on parent_in in parent process #reading child_in returns data parent has written parent_out end child_read.close child_write.close #write data parent_out here have appear on child_in in child #reading parent_in data child has written child_out
as far know there no cross process concurrency primitives built ruby.
Comments
Post a Comment