Class: Zold::ThreadPool

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

Overview

Thread pool

Instance Method Summary collapse

Constructor Details

#initialize(title, log: Log::NULL) ⇒ ThreadPool

Returns a new instance of ThreadPool.



34
35
36
37
38
39
# File 'lib/zold/thread_pool.rb', line 34

def initialize(title, log: Log::NULL)
  @title = title
  @log = log
  @threads = []
  @start = Time.now
end

Instance Method Details

#addObject

Add a new thread



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/zold/thread_pool.rb', line 70

def add
  raise 'Block must be given to start()' unless block_given?
  latch = Concurrent::CountDownLatch.new(1)
  thread = Thread.start do
    Thread.current.name = @title
    VerboseThread.new(@log).run do
      latch.count_down
      yield
    end
  end
  latch.wait
  Thread.current.thread_variable_set(
    :kids,
    (Thread.current.thread_variable_get(:kids) || []) + [thread]
  )
  @threads << thread
end

#countObject

How many threads are in there



122
123
124
# File 'lib/zold/thread_pool.rb', line 122

def count
  @threads.count
end

#exists?(name) ⇒ Boolean

A thread with this name exists?

Returns:

  • (Boolean)


127
128
129
# File 'lib/zold/thread_pool.rb', line 127

def exists?(name)
  !@threads.find { |t| t.name == name }.nil?
end

#join(sec) ⇒ Object



88
89
90
# File 'lib/zold/thread_pool.rb', line 88

def join(sec)
  @threads.each { |t| t.join(sec) }
end

#killObject

Kill them all immediately and close the pool



93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/zold/thread_pool.rb', line 93

def kill
  if @threads.empty?
    @log.debug("Thread pool \"#{@title}\" terminated with no threads")
    return
  end
  @log.debug("Stopping \"#{@title}\" thread pool with #{@threads.count} threads: \
#{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}...")
  start = Time.new
  begin
    @threads.each do |t|
      t.join(0.1)
    end
  ensure
    @threads.each do |t|
      (t.thread_variable_get(:kids) || []).each(&:kill)
      t.kill
      sleep(0.001) while t.alive? # I believe it's a bug in Ruby, this line fixes it
      Thread.current.thread_variable_set(
        :kids,
        (Thread.current.thread_variable_get(:kids) || []) - [t]
      )
    end
    @log.debug("Thread pool \"#{@title}\" terminated all threads in #{Age.new(start)}, \
it was alive for #{Age.new(@start)}: #{@threads.map { |t| "#{t.name}/#{t.status}" }.join(', ')}")
    @threads.clear
  end
end

#run(threads, set = (0..threads - 1).to_a) ⇒ Object

Run this code in many threads



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/zold/thread_pool.rb', line 42

def run(threads, set = (0..threads - 1).to_a)
  raise "Number of threads #{threads} has to be positive" unless threads.positive?
  list = set.dup
  total = [threads, set.count].min
  if total == 1
    list.each_with_index { |r, i| yield(r, i) }
  elsif total.positive?
    idx = Concurrent::AtomicFixnum.new
    mutex = Mutex.new
    latch = Concurrent::CountDownLatch.new(total)
    total.times do |i|
      add do
        Thread.current.name = "#{@title}-#{i}"
        loop do
          r = mutex.synchronize { list.pop }
          break if r.nil?
          yield(r, idx.increment - 1)
        end
      ensure
        latch.count_down
      end
    end
    latch.wait
    kill
  end
end

#to_jsonObject

As a hash map



132
133
134
135
136
137
138
139
140
141
# File 'lib/zold/thread_pool.rb', line 132

def to_json
  @threads.map do |t|
    {
      name: t.name,
      status: t.status,
      alive: t.alive?,
      vars: Hash[t.thread_variables.map { |v| [v.to_s, t.thread_variable_get(v)] }]
    }
  end
end

#to_sObject

As a text



144
145
146
147
148
149
150
151
152
# File 'lib/zold/thread_pool.rb', line 144

def to_s
  @threads.map do |t|
    [
      "#{t.name}: status=#{t.status}; alive=#{t.alive?}",
      'Vars: ' + t.thread_variables.map { |v| "#{v}=\"#{t.thread_variable_get(v)}\"" }.join('; '),
      t.backtrace.nil? ? 'NO BACKTRACE' : "  #{t.backtrace.join("\n  ")}"
    ].join("\n")
  end
end