lib/threads.rb in threads-0.2.0 vs lib/threads.rb in threads-0.3.0
- old
+ new
@@ -21,18 +21,23 @@
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
require 'concurrent'
+require 'backtrace'
# Threads.
# Author:: Yegor Bugayenko (yegor256@gmail.com)
# Copyright:: Copyright (c) 2018 Yegor Bugayenko
# License:: MIT
class Threads
- def initialize(total = Concurrent.processor_count * 8)
+ def initialize(total = Concurrent.processor_count * 8, log: STDOUT)
+ raise "Total can't be nil" if total.nil?
+ raise "Total can't be negative or zero: #{total}" unless total.positive?
@total = total
+ raise "Log can't be nil" if log.nil?
+ @log = log
end
def assert(reps = @total)
if reps < @total
raise "Repetition counter #{reps} can't be smaller than #{@total}"
@@ -49,11 +54,11 @@
r = rep.increment
break if r > reps
begin
yield(t, r - 1)
rescue StandardError => e
- puts Backtrace.new(e)
+ print(Backtrace.new(e))
raise e
end
end
done.increment
end
@@ -61,7 +66,17 @@
latch.count_down
pool.shutdown
raise "Can't stop the pool" unless pool.wait_for_termination(30)
return if done.value == @total
raise "Only #{done.value} out of #{@total} threads completed successfully"
+ end
+
+ private
+
+ def print(msg)
+ if @log.respond_to?(:error)
+ @log.error(msg)
+ elsif @log.respond_to?(:puts)
+ @log.puts(msg)
+ end
end
end