Class: Zold::Farm

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/node/farm.rb

Overview

Farm

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(invoice, log: Log::Quiet.new) ⇒ Farm

Returns a new instance of Farm.



33
34
35
36
37
38
39
40
41
# File 'lib/zold/node/farm.rb', line 33

def initialize(invoice, log: Log::Quiet.new)
  @log = log
  @invoice = invoice
  @scores = []
  @threads = []
  @best = []
  @best << Score::ZERO
  @semaphore = Mutex.new
end

Instance Attribute Details

#bestObject (readonly)

Returns the value of attribute best.



32
33
34
# File 'lib/zold/node/farm.rb', line 32

def best
  @best
end

Instance Method Details

#start(host, port, strength: 8, threads: 8) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/zold/node/farm.rb', line 51

def start(host, port, strength: 8, threads: 8)
  @log.debug('Zero-threads farm won\'t score anything!') if threads.zero?
  @scores = Queue.new
  first = Score.new(Time.now, host, port, @invoice, strength: strength)
  @best = [first]
  @scores << first
  @threads = (1..threads).map do |t|
    Thread.new do
      Thread.current.name = "farm-#{t}"
      loop do
        s = @scores.pop
        next unless s.valid?
        @semaphore.synchronize do
          before = @best.map(&:value).max
          @best << s
          after = @best.map(&:value).max
          @best.reject! { |b| b.value < after }
          @log.debug("#{Thread.current.name}: best is #{@best[0]}") if before != after
        end
        if @scores.length < 4
          @scores << Score.new(
            Time.now, host, port, @invoice,
            strength: strength
          )
        end
        @scores << s.next
      end
    end
  end
  @log.debug("Farm started with #{threads} threads at #{host}:#{port}")
end

#stopObject



83
84
85
86
87
88
89
# File 'lib/zold/node/farm.rb', line 83

def stop
  @threads.each do |t|
    t.exit
    @log.debug("Thread #{t.name} terminated")
  end
  @log.debug('Farm stopped')
end

#to_jsonObject



43
44
45
46
47
48
49
# File 'lib/zold/node/farm.rb', line 43

def to_json
  {
    threads: @threads.count,
    scores: @scores.size,
    best: @best.count
  }
end