361.patch

Zachary Scott, 08/15/2013 06:00 AM

Download (3.34 KB)

View differences:

lib/thread.rb
250 250
  def num_waiting
251 251
    @num_waiting
252 252
  end
253

  
254
  #
255
  # Pops and yields each element in the queue. Blocks when the queue
256
  # is empty unless +non_block+ is +true+.
257
  #
258
  # Returns an +Enumerator+ if no block is given.
259
  #
260
  def each(non_block=false)
261
    return to_enum(:each, non_block){ size } unless block_given?
262
    loop do
263
      yield pop(non_block)
264
    end
265
  rescue ThreadError
266
    raise unless non_block
267
  end
253 268
end
254 269

  
255 270
#
test/thread/test_queue.rb
133 133
    assert_same q, retval
134 134
  end
135 135

  
136
  def test_queue_each
137
    q = Queue.new
138
    q.push(1)
139
    q.push(2)
140
    results = []
141
    doubler = Thread.new do
142
      q.each do |n|
143
        results << n + n
144
      end
145
    end
146
    sleep 0.01 until doubler.stop?
147
    assert_equal [2, 4], results
148
    q.push(3)
149
    sleep 0.01 until doubler.stop?
150
    assert_equal [2, 4, 6], results
151
  end
152

  
153
  def test_queue_each_enumerator
154
    q = Queue.new
155
    q.push(1)
156
    q.push(2)
157
    e = q.each
158
    assert_instance_of Enumerator, e
159
    assert_equal 2, e.size
160
    assert_equal 1, e.next
161
    assert_equal 2, e.next
162
    assert_equal 0, e.size
163
  end
164

  
165
  def test_queue_each_blocking_passes_thread_errors_through
166
    q = Queue.new
167
    q.push(1)
168
    doubler = Thread.new do
169
      q.each(false) do |n|
170
        raise ThreadError
171
      end
172
    end
173
    assert_raises(ThreadError) do
174
      doubler.join
175
    end
176
  end
177

  
178
  def test_queue_each_nonblock
179
    q = Queue.new
180
    q.push(1)
181
    q.push(2)
182
    results = []
183
    doubler = Thread.new do
184
      q.each(true) do |n|
185
        results << n + n
186
      end
187
    end
188
    doubler.abort_on_exception = true
189
    sleep 0.01 until doubler.stop?
190
    assert_equal [2, 4], results
191
    assert !doubler.alive?, "Thread should have ended"
192
  end
136 193
end
137
- 
test/thread/test_queue.rb
150 150
    assert_equal [2, 4, 6], results
151 151
  end
152 152

  
153
  def test_queue_each_break
154
    q = Queue.new
155
    q.push(1)
156
    q.push(:stop)
157
    q.push(2)
158
    results = []
159
    doubler = Thread.new do
160
      q.each do |n|
161
        break if n == :stop
162
        results << n + n
163
      end
164
    end
165
    doubler.join
166
    assert_equal [2], results
167
    assert_equal 2, q.pop
168
  end
169

  
153 170
  def test_queue_each_enumerator
154 171
    q = Queue.new
155 172
    q.push(1)
156
-