Class: Zold::Farm

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

Overview

Farm

Defined Under Namespace

Classes: Empty

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Farm.



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

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.



39
40
41
# File 'lib/zold/node/farm.rb', line 39

def best
  @best
end

Instance Method Details

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



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/zold/node/farm.rb', line 58

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



90
91
92
93
94
95
96
# File 'lib/zold/node/farm.rb', line 90

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

#to_jsonObject



50
51
52
53
54
55
56
# File 'lib/zold/node/farm.rb', line 50

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