Skip to content

Commit ef1eb0e

Browse files
AlexanderZagaynovpitr-ch
authored andcommitted
autoname MRI threads
1 parent e5de92d commit ef1eb0e

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

lib/concurrent/executor/ruby_thread_pool_executor.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ def ns_initialize(opts)
131131
@scheduled_task_count = 0
132132
@completed_task_count = 0
133133
@largest_length = 0
134+
@workers_counter = 0
134135
@ruby_pid = $$ # detects if Ruby has forked
135136

136137
@gc_interval = opts.fetch(:gc_interval, @idletime / 2.0).to_i # undocumented
@@ -224,7 +225,8 @@ def ns_worker_died(worker)
224225
def ns_add_busy_worker
225226
return if @pool.size >= @max_length
226227

227-
@pool << (worker = Worker.new(self))
228+
@workers_counter += 1
229+
@pool << (worker = Worker.new(self, id: @workers_counter))
228230
@largest_length = @pool.length if @pool.length > @largest_length
229231
worker
230232
end
@@ -284,6 +286,7 @@ def ns_reset_if_forked
284286
@scheduled_task_count = 0
285287
@completed_task_count = 0
286288
@largest_length = 0
289+
@workers_counter = 0
287290
@ruby_pid = $$
288291
end
289292
end
@@ -292,11 +295,12 @@ def ns_reset_if_forked
292295
class Worker
293296
include Concern::Logging
294297

295-
def initialize(pool)
298+
def initialize(pool, id: nil)
296299
# instance variables accessed only under pool's lock so no need to sync here again
297300
@queue = Queue.new
298301
@pool = pool
299302
@thread = create_worker @queue, pool, pool.idletime
303+
@thread.name = [pool.name, self.class.name, id].compact.join('-')
300304
end
301305

302306
def <<(message)

spec/concurrent/executor/ruby_thread_pool_executor_spec.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,37 @@ module Concurrent
5454
block.count_down
5555
end
5656
end
57+
58+
context 'threads naming' do
59+
subject do
60+
opts = { min_threads: 2 }
61+
opts[:name] = pool_name if pool_name
62+
described_class.new(opts)
63+
end
64+
65+
let(:names) { Concurrent::Set.new }
66+
67+
before do
68+
subject.post(names) { |names| names << Thread.current.name }
69+
subject.post(names) { |names| names << Thread.current.name }
70+
subject.shutdown
71+
subject.wait_for_termination(pool_termination_timeout)
72+
expect(names.size).to eq 2
73+
end
74+
75+
context 'without pool name' do
76+
let(:pool_name) { }
77+
it 'sets counted name' do
78+
expect(names.all? { |name| name =~ /^Concurrent.*Worker-\d+$/ }).to be true
79+
end
80+
end
81+
82+
context 'with pool name' do
83+
let(:pool_name) { 'MyExecutor' }
84+
it 'sets counted name' do
85+
expect(names.all? { |name| name =~ /^MyExecutor-Concurrent.*Worker-\d+$/ }).to be true
86+
end
87+
end
88+
end
5789
end
5890
end

0 commit comments

Comments
 (0)