DRb & Threads

I have a Ruby application that is comprised of two threads. One thread
updates a data class and the other thread is the DRb server associated with
the data class. When my client accesses the data class through the DRb
server, do I need to be concerned about controlling access to the data class
with a mutex?

Currently, I am only retrieving data with my DRb client, but this will
change in the near future. If I am updating the data class via the DRb
client, I assume I will need to take precautions to protect the data class?

If you use a mutex in this situation, whom gets blocked by the mutex and how
does it effect the DRb operation/client?

Thanks.

Hi,

Currently, I am only retrieving data with my DRb client, but this will
change in the near future. If I am updating the data class via the DRb
client, I assume I will need to take precautions to protect the data class?

If you use a mutex in this situation, whom gets blocked by the mutex and how
does it effect the DRb operation/client?

Yes, you need it and work well.

count.rb

require ‘thread’

class Counter
def initialize(n = 0)
@value = n
end
attr_reader :value
alias :to_i :value

def succ
it = @value
sleep 0.5
@value = it + 1
puts @value
return @value
end
end

class MutexCounter < Counter
def initialize(n = 0)
super(n)
@mutex = Mutex.new
end

def succ
@mutex.synchronize do
return super
end
end
end

if FILE == $0
require ‘drb/drb’

class Counter
include DRbUndumped
end

here = ARGV.shift || ‘druby://localhost:12345’

front = Hash.new
front[:Counter] = Counter.new
front[:MutexCounter] = MutexCounter.new

DRb.start_service(here, front)
puts DRb.uri
DRb.thread.join
end

test_count.rb

require ‘drb/drb’

def test(counter, n = 10)
n.times do |i|
puts “#{i}: #{counter.succ}”
end
end

there = ARGV.shift || ‘druby://localhost:12345’

DRb.start_service
front = DRbObject.new(nil, there)

puts “Counter”
test(front[:Counter])

puts “MutexCounter”
test(front[:MutexCounter])

···

run scripts.

Terminal 1
% ruby count.rb

Terminal 2 and 3
% ruby test_countr.b

Terminal 2 Terminal 3


Counter Counter
0: 1 0: 2
1: 2 1: 3
2: 3 2: 4
3: 4 3: 5
4: 5 4: 6
5: 6 5: 7
6: 7 6: 8
7: 8 7: 9
8: 9 8: 10
9: 10 9: 11
MutexCounter MutexCounter
0: 1 0: 2
1: 3 1: 4
2: 5 2: 6
3: 7 3: 8
4: 9 4: 10
5: 11 5: 12
6: 13 6: 14
7: 15 7: 16
8: 17 8: 18
9: 19 9: 20