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, cache, log: Log::Quiet.new) ⇒ Farm

Returns a new instance of Farm.



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

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

Instance Attribute Details

#bestObject (readonly)

Returns the value of attribute best.



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

def best
  @best
end

Instance Method Details

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



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
89
90
91
92
93
94
# File 'lib/zold/node/farm.rb', line 59

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

#stopObject



96
97
98
99
100
101
102
# File 'lib/zold/node/farm.rb', line 96

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

#to_jsonObject



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

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