1=begin
2 distributed Ruby --- NamedObject Sample
3 	Copyright (c) 2000-2001 Masatoshi SEKI
4=end
5
6=begin
7How to play.
8
9* start server
10 Terminal 1
11 | % ruby name.rb druby://yourhost:7640
12 | druby://yourhost:7640
13 | [return] to exit
14
15* start client
16 Terminal 2
17 | % ruby namec.rb druby://yourhost:7640
18 | #<DRb::DRbObject:0x40164174 @uri="druby://yourhost:7640", @ref="seq">
19 | #<DRb::DRbObject:0x40163c9c @uri="druby://yourhost:7640", @ref="mutex">
20 | 1
21 | 2
22 | [return] to continue
23
24* restart server
25 Terminal 1
26 type [return]
27 | % ruby name.rb druby://yourhost:7640
28 | druby://yourhost:7640
29 | [return] to exit
30
31* continue client
32 Terminal 2
33 type [return]
34 | 1
35 | 2
36=end
37
38require 'thread.rb'
39require 'drb/drb'
40
41module DRbNamedObject
42  DRbNAMEDICT = {}
43  attr_reader(:drb_name)
44
45  def drb_name=(name)
46    @drb_name = name
47    Thread.exclusive do
48      raise(IndexError, name) if DRbNAMEDICT[name]
49      DRbNAMEDICT[name] = self
50    end
51  end
52end
53
54class DRbNamedIdConv < DRb::DRbIdConv
55  def initialize
56    @dict = DRbNamedObject::DRbNAMEDICT
57  end
58
59  def to_obj(ref)
60    @dict.fetch(ref) do super end
61  end
62
63  def to_id(obj)
64    if obj.kind_of? DRbNamedObject
65      return obj.drb_name
66    else
67      return super
68    end
69  end
70end
71
72class Seq
73  include DRbUndumped
74  include DRbNamedObject
75
76  def initialize(v, name)
77    @counter = v
78    @mutex = Mutex.new
79    self.drb_name = name
80  end
81
82  def next_value
83    @mutex.synchronize do
84      @counter += 1
85      return @counter
86    end
87  end
88end
89
90class Front
91  def initialize
92    seq = Seq.new(0, 'seq')
93    mutex = Mutex.new
94    mutex.extend(DRbUndumped)
95    mutex.extend(DRbNamedObject)
96    mutex.drb_name = 'mutex'
97    @name = {}
98    @name['seq'] = seq
99    @name['mutex'] = mutex
100  end
101
102  def [](k)
103    @name[k]
104  end
105end
106
107if __FILE__ == $0
108  uri = ARGV.shift
109
110  name_conv = DRbNamedIdConv.new
111
112  DRb.install_id_conv(name_conv)
113  DRb.start_service(uri, Front.new)
114  puts DRb.uri
115  DRb.thread.join
116end
117
118