require 'thread'




class BucketStore

  
  
  def initialize nbuckets
    
    @buckets = (0...nbuckets).map { rand(1024) }

    
    @mutex = Mutex.new
  end

  
  def buckets
    @mutex.synchronize { Array.new(@buckets) }
  end

  
  
  def transfer destination, source, amount
    
    return nil if destination == source

    @mutex.synchronize do
      
      amount = [amount, @buckets[source]].min

      @buckets[source] -= amount
      @buckets[destination] += amount
    end
    nil
  end
end


bucket_store = BucketStore.new 8


TOTAL = bucket_store.buckets.inject { |a, b| a += b }


Thread.new do
  loop do
    
    buckets = bucket_store.buckets
    first = rand buckets.length
    second = rand buckets.length

    
    first, second = second, first if buckets[first] > buckets[second]

    
    bucket_store.transfer first, second, (buckets[second] - buckets[first]) / 2
  end
end


Thread.new do
  loop do
    
    buckets = bucket_store.buckets
    first = rand buckets.length
    second = rand buckets.length

    
    bucket_store.transfer first, second, rand(buckets[second])
  end
end


loop do
  sleep 1

  buckets = bucket_store.buckets

  
  
  
  n = buckets.inject { |a, b| a += b }

  
  printf , (buckets.map { |v| sprintf , v }.join ), n

  if n!= TOTAL
    
    $stderr.puts 
    exit 1
  end
end