File: multiton2.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (590 lines) | stat: -rw-r--r-- 11,198 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590

module Multiton

  #  disable build-in copying methods
  def clone
    raise TypeError, "can't clone Multiton #{self}"
  end

  def dup
    raise TypeError, "can't dup Multiton #{self}"
  end

  protected  #  default marshalling strategy
  def _dump(depth=-1)
    Marshal.dump(@multiton_initializer)
  end

  #

  class << self
    private
    def append_features(mod)
      #  help out people counting on transitive mixins
      unless mod.instance_of?(Class)
        raise TypeError, "Inclusion of Multiton in module #{mod}"
      end
      super
    end

    def included(klass)
      # gracefully handle multiple inclusions of Multiton
      unless class << klass; include?(Multiton::ClassMethods) end
        klass.private_class_method  :new, :allocate
        klass.extend Multiton::ClassMethods
      end
    end
  end

  #

  module ClassMethods

    def instance(*e)
      arg = multiton_id(e)
      @multiton_instance.fetch(arg) do
        @multiton_mutex[arg].synchronize do
          @multiton_instance.fetch(arg) do
            val = @multiton_instance[arg] = new(*e)
            val.instance_variable_set(:@multiton_initializer,e)
            @multiton_mutex.initialized(arg)
            val
          end
        end
      end
    end

    def initialized?(*e)
      @multiton_instance.key?(multiton_id(e))
    end

    protected
    def reinitialize
      @multiton_instance.clear
      @multiton_mutex.clear
    end

    def _load(str)
      instance(*Marshal.load(str))
    end

    private
    def multiton_id(e)
      e
    end

    def initialize_copy(orig)
      super
      Multiton::ClassMethods.extended(self)
    end

    def inherited(sub)
      super
      Multiton::ClassMethods.extended(sub)
    end

    class << self
      protected
      def extended(klass)
        klass.class_eval do
          @multiton_instance = Hash.new
          @multiton_mutex = InstanceMutex.new

          private
          # Defining  marshal_dump & marshal_load instance methods introduces
          # a loop hole to create additonal instances. Providing a private
          # marshal_dump method forces Ruby to fall back on the _dump & _load
          # marshalling scheme. When $VERBOSE == true issue a method re-
          # definition warning for (re)defining marshal_dump.
          def marshal_dump(depth = -1)
            raise TypeError, "don't use marshal_load + marshal_dump marshalling"
          end
        end
      end

      class InstanceMutex < Hash
        def initialize
          @global = Mutex.new
        end

        def initialized(arg)
          store(arg,DummyMutex)
        end

        def (DummyMutex = Object.new).synchronize
          yield
        end

        def default(arg)
          @global.synchronize { fetch(arg) { store(arg,Mutex.new) }}
        end
      end
    end
  end
end


























module Multiton
  #  disable build-in copying methods
  def clone
    raise TypeError, "can't clone Multiton #{self}"
  end

  def dup
    raise TypeError, "can't dup Multiton #{self}"
  end

  protected  #  default marshalling strategy
  def _dump(depth=-1)
    Marshal.dump(@multiton_initializer)
  end
end

class << Multiton
  private
  def append_features(mod)
    #  help out people counting on transitive mixins
    unless mod.instance_of?(Class)
      raise TypeError, "Inclusion of Multiton in module #{mod}"
    end
    super
  end

  def included(klass)
    # gracefully handle multiple inclusions of Multiton
    unless class << klass; include?(Multiton::ClassMethods) end
      klass.private_class_method  :new,:allocate
      klass.extend Multiton::ClassMethods
    end
  end
end

module Multiton::ClassMethods
  def instance(*e)
    arg = multiton_id(e)
    @multiton_instance.fetch(arg) {
      @multiton_mutex[arg].synchronize {
        @multiton_instance.fetch(arg) {
          val = @multiton_instance[arg] = new(*e)
          val.instance_variable_set(:@multiton_initializer,e)
          @multiton_mutex.initialized(arg)
          val
    }}}
  end

  def initialized?(*e)
    @multiton_instance.key?(multiton_id(e))
  end

  protected
  def reinitialize
    @multiton_instance.clear
    @multiton_mutex.clear
  end

  def _load(str)
    instance(*Marshal.load(str))
  end

  private
  def multiton_id(e)
    e
  end

  def initialize_copy(orig)
    super
    Multiton::ClassMethods.extended(self)
  end

  def inherited(sub)
    super
    Multiton::ClassMethods.extended(sub)
  end
end

class << Multiton::ClassMethods
  protected
  def extended(klass)
    klass.class_eval do
      @multiton_instance = Hash.new
      @multiton_mutex = InstanceMutex.new

      private
      # Defining  marshal_dump & marshal_load instance methods introduces
      # a loop hole to create additonal instances. Providing a private
      # marshal_dump method forces Ruby to fall back on the _dump & _load
      # marshalling scheme. When $VERBOSE == true issue a method re-
      # definition warning for (re)defining marshal_dump.
      def marshal_dump(depth = -1)
        raise TypeError, "don't use marshal_load + marshal_dump marshalling"
      end
    end
  end

  class InstanceMutex < Hash
    def initialize
      @global = Mutex.new
    end

    def initialized(arg)
      store(arg,DummyMutex)
    end

    def (DummyMutex = Object.new).synchronize
      yield
    end

    def default(arg)
      @global.synchronize { fetch(arg) { store(arg,Mutex.new) }}
    end
  end
end




### Simple marshalling test #######
class A
  def initialize(a,*e)
    @e = a
  end

  include Multiton

end




C = Class.new(A.clone)
s = C.instance('a','b')

raise unless Marshal.load(Marshal.dump(s)) == s


### Interdependent initialization example and threading benchmark ###

class Regular_SymPlane
  def self.multiton_id(e)
      a,b = e
      (a+b - 1)*(a+b )/2  + (a > b ? a : b)
  end

  def initialize(a,b)
    klass = self.class
    if a < b
      @l =  b > 0 ?  klass.instance(a,b-1) : nil
      @r =  a > 0 ?  klass.instance(a-1,b) : nil
    else
      @l =  a > 0 ?  klass.instance(a-1,b) : nil
      @r =  b > 0 ?  klass.instance(a,b-1) : nil
    end
  end

  include Multiton
end



def nap
  # Thread.pass
  sleep(rand(0.01))
end

class SymPlane < Regular_SymPlane
  @m = Mutex.new
  @count = 0
end

class << SymPlane
  attr_reader :count
  def reinitialize
    super
    @m = Mutex.new
    @count = 0
  end
  def inherited(sub_class)
    super
    sub_class.instance_eval { @m = Mutex.new; @count = 0 }
  end

  def multiton_id(e)
    nap()
    super
  end

  def new(*e)
    super
  ensure
    nap()
    @m.synchronize { p @count if (@count += 1) % 15 == 0 }
  end

  def run(k)
    threads = 0
    max = k * (k+1) / 2
    puts ""
    while count() < max
      Thread.new { threads+= 1; instance(rand(30),rand(30)) }
    end
    puts "\nThe simulation created #{threads} threads"
  end
end


require 'Benchmark'
include Benchmark

bmbm do |x|
  x.report('Initialize 465 SymPlane instances') { SymPlane.run(30) }
  x.report('Reinitialize ') do
    sleep 3
    SymPlane.reinitialize
  end
end

















module Multiton
  #  disable build-in copying methods
  def clone
    raise TypeError, "can't clone Multiton #{self}"
  end

  def dup
    raise TypeError, "can't dup Multiton #{self}"
  end

  protected  #  default marshalling strategy
  def _dump(depth=-1)
    Marshal.dump(@multiton_initializer)
  end
end

class << Multiton
  private
  def append_features(mod)
    #  help out people counting on transitive mixins
    unless mod.instance_of?(Class)
      raise TypeError, "Inclusion of Multiton in module #{mod}"
    end
    super
  end

  def included(klass)
    # gracefully handle multiple inclusions of Multiton
    unless class << klass; include?(Multiton::ClassMethods) end
      klass.private_class_method  :new, :allocate
      klass.extend Multiton::ClassMethods
    end
  end
end


module Multiton::ClassMethods
  class SyncHash < Hash
    def initialize
      @global = Mutex.new
      super {|a,b| @global.synchronize {|| fetch(b) {|| a[b]= yield }}}
    end
  end

  PoolInstance = SyncHash.new{ Hash.new }
  PoolInstanceMutex = SyncHash.new{ SyncHash.new{ Mutex.new }}
  def (DummyMutex = Object.new).synchronize
    yield
  end

  def instance(*e)
    arg = multiton_id(e)
    (@multiton_instance ||= PoolInstance[self]).fetch(arg) {
      (@multiton_mutex ||= PoolInstanceMutex[self])[arg].synchronize {
        @multiton_instance.fetch(arg) {
          val = @multiton_instance[arg] = new(*e)
          val.instance_variable_set(:@multiton_initializer,e)
          @multiton_mutex[arg]= DummyMutex
          val
    }}}
  end

  def initialized?(*e)
    # the method is not thread safe ...
    (@multiton_instance ||= PoolInstance[self]).key?(multiton_id(e))
  end

  protected
  def reinitialize
    (@multiton_instance ||= PoolInstance[self]).clear
    (@multiton_mutex ||= PoolInstanceMutex[self]).clear
  end

  def _load(str)
    instance(*Marshal.load(str))
  end

  private
  def multiton_id(e)
    e
  end

  # Defining  marshal_dump & marshal_load instance methods introduces
  # a loop hole to create additonal instances. Providing a private
  # marshal_dump method forces Ruby to fall back on the _dump & _load
  # marshalling scheme. When $VERBOSE == true issue a method re-
  # definition warning for (re)defining marshal_dump.
  def self.extended(klass)
    klass.class_eval do
      private
      def marshal_dump(depth = -1)
        raise TypeError, "don't use marshal_load + marshal_dump marshalling"
      end
    end
  end
  private_class_method :extended

end








### Simple marshalling test #######
class A
  def initialize(a,*e)
    @e = a
  end

  include Multiton

end




C = Class.new(A.clone)
s = C.instance('a','b')

raise unless Marshal.load(Marshal.dump(s)) == s


### Interdependent initialization example and threading benchmark ###

class Regular_SymPlane
  def self.multiton_id(e)
      a,b = e
      (a+b - 1)*(a+b )/2  + (a > b ? a : b)
  end

  def initialize(a,b)
    klass = self.class
    if a < b
      @l =  b > 0 ?  klass.instance(a,b-1) : nil
      @r =  a > 0 ?  klass.instance(a-1,b) : nil
    else
      @l =  a > 0 ?  klass.instance(a-1,b) : nil
      @r =  b > 0 ?  klass.instance(a,b-1) : nil
    end
  end

  include Multiton
end



def nap
  # Thread.pass
  sleep(rand(0.01))
end

class SymPlane < Regular_SymPlane
  @m = Mutex.new
  @count = 0
end

class << SymPlane
  attr_reader :count
  def reinitialize
    super
    @m = Mutex.new
    @count = 0
  end
  def inherited(sub_class)
    super
    sub_class.instance_eval { @m = Mutex.new; @count = 0 }
  end

  def multiton_id(e)
    nap()
    super
  end

  def new(*e)
    super
  ensure
    nap()
    @m.synchronize { p @count if (@count += 1) % 15 == 0 }
  end

  def run(k)
    threads = 0
    max = k * (k+1) / 2
    puts ""
    while count() < max
      Thread.new { threads+= 1; instance(rand(k),rand(k)) }
    end
    puts "\nThe simulation created #{threads} threads"
  end
end


require 'Benchmark'
include Benchmark

bmbm do |x|
  x.report('Initialize 465 SymPlane instances') { SymPlane.run(30) }
  x.report('Reinitialize ') do
    sleep 3
    SymPlane.reinitialize
  end
end