Class: Dunder::Group

Inherits:
Object
  • Object
show all
Defined in:
lib/dunder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max) ⇒ Group

Returns a new instance of Group.

Raises:

  • (ArgumentError)


51
52
53
54
55
56
57
# File 'lib/dunder.rb', line 51

def initialize(max)
  raise ArgumentError,"You must specify a maximum number of threads for this group #{max}" unless max && max.is_a?(Integer)
  @max = max
  @running = 0
  @waiting = []
  @mutex = Mutex.new
end

Instance Attribute Details

#maxObject (readonly)

Returns the value of attribute max.



49
50
51
# File 'lib/dunder.rb', line 49

def max
  @max
end

#nameObject (readonly)

Returns the value of attribute name.



49
50
51
# File 'lib/dunder.rb', line 49

def name
  @name
end

Instance Method Details

#finish_threadObject



98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/dunder.rb', line 98

def finish_thread
  thread = Thread.current
  @mutex.synchronize {
    @running -= 1
    unless @waiting.empty?
      # Schedule the next job
      t = @waiting.shift
      @running += 1
      t.wakeup
    end 
  }
end

#init_threadObject



85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/dunder.rb', line 85

def init_thread
  thread = Thread.current
  waiting = false
  @mutex.synchronize {
    if waiting = (@running >= @max)
      @waiting.push(thread)
    else
      @running += 1
    end
  }
  Thread.stop if waiting
end

#lazy_load(&block) ⇒ Object



71
72
73
# File 'lib/dunder.rb', line 71

def lazy_load(&block)
  Future.new(self,&block)
end

#runningObject



59
60
61
62
63
# File 'lib/dunder.rb', line 59

def running
  @mutex.synchronize {
    @running
  }
end

#start_thread(&block) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/dunder.rb', line 75

def start_thread(&block)
  group = self
  Thread.start {
    group.init_thread
    value = block.call
    group.finish_thread
    value
  }
end

#waitingObject



65
66
67
68
69
# File 'lib/dunder.rb', line 65

def waiting
  @mutex.synchronize {
    @waiting
  }
end