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.



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

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.



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

def best
  @best
end

Instance Method Details

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



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
95
96
97
98
# File 'lib/zold/node/farm.rb', line 60

def start(host, port, strength: 8, threads: 8)
  @log.debug('Zero-threads farm won\'t score anything!') if threads.zero?
  @scores = Queue.new
  h = history(threads)
  h.each { |s| @scores << s }
  @best << (h[0] || Score.new(Time.now, host, port, @invoice, strength: strength))
  @log.info("#{@scores.size} scores pre-loaded, the best is: #{@best[0]}")
  @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 unless s.host == host
          next unless s.port == port
          next if s.expired?(20)
          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



100
101
102
103
104
105
106
# File 'lib/zold/node/farm.rb', line 100

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

#to_jsonObject



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

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