Class: Ups

Inherits:
SomeSingletonClass show all
Defined in:
lib/singleton.rb

Constant Summary

Constants included from Singleton

Singleton::FirstInstanceCall

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Singleton

__init__, #_dump, #clone, #dup

Constructor Details

#initializeUps

Returns a new instance of Ups.



215
216
217
218
# File 'lib/singleton.rb', line 215

def initialize
  self.class.__sleep
  puts "initialize called by thread ##{Thread.current[:i]}"
end

Class Method Details

.__sleepObject



233
234
235
# File 'lib/singleton.rb', line 233

def __sleep
  sleep(rand(0.08))
end

._instantiate?Boolean

Returns:

  • (Boolean)


222
223
224
225
226
227
228
229
230
231
# File 'lib/singleton.rb', line 222

def _instantiate?
  @enter.push Thread.current[:i]
  while false.equal?(@__instance__)
    Thread.critical = false
    sleep 0.08
    Thread.critical = true
  end
  @leave.push Thread.current[:i]
  @__instance__
end

.instantiate_allObject



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/singleton.rb', line 249

def instantiate_all
  @enter = []
  @leave = []
  1.upto(9) {|i|
    Thread.new {
      begin
        Thread.current[:i] = i
        __sleep
        instance
      rescue RuntimeError => mes
        puts mes
      end
    }
  }
  puts "Before there were #{num_of_instances(self)}"
  sleep 3
  puts "Now there is #{num_of_instances(self)}"
  puts "#{@enter.join '; '} was the order of threads entering the waiting loop"
  puts "#{@leave.join '; '} was the order of threads leaving the waiting loop"
end

.newObject



237
238
239
240
241
242
243
244
245
246
247
# File 'lib/singleton.rb', line 237

def new
  begin
    __sleep
    raise  "boom - thread ##{Thread.current[:i]} failed to create instance"
  ensure
    # simple flip-flop
    class << self
      remove_method :new
    end
  end
end