Skip to content

Commit

Permalink
also set parallel_worker_number when working directly
Browse files Browse the repository at this point in the history
  • Loading branch information
Sean Walbran committed Jun 1, 2016
1 parent d82300b commit e576c6b
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
3 changes: 3 additions & 0 deletions lib/parallel.rb
Expand Up @@ -277,6 +277,7 @@ def add_progress_bar!(job_factory, options)
end

def work_direct(job_factory, options, &block)
Thread.current[:parallel_worker_number] = 0
results = []
while set = job_factory.next
item, index = set
Expand All @@ -285,6 +286,8 @@ def work_direct(job_factory, options, &block)
end
end
results
ensure
Thread.current[:parallel_worker_number] = nil
end

def work_in_threads(job_factory, options, &block)
Expand Down
3 changes: 1 addition & 2 deletions spec/cases/with_worker_number.rb
Expand Up @@ -3,9 +3,8 @@
method = ENV.fetch('METHOD')
in_worker_type = "in_#{ENV.fetch('WORKER_TYPE')}".to_sym

result = Parallel.public_send(method, 1..100, in_worker_type => 4) do
Parallel.public_send(method, 1..100, in_worker_type => 4) do
sleep 0.1 # so all workers get started
print Thread.current[:parallel_worker_number]
nil
end

8 changes: 7 additions & 1 deletion spec/parallel_spec.rb
Expand Up @@ -261,11 +261,17 @@ def cpus
`METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_exception_in_start_before_finish.rb 2>&1`.should == '3 called'
end

it "has access to thread local parallel_worker_number with #{type}" do
it "has access to thread local parallel_worker_number with 4 #{type}" do
out = `METHOD=map WORKER_TYPE=#{type} ruby spec/cases/with_worker_number.rb`
out.should =~ /\A[0123]+\z/
%w(0 1 2 3).each { |number| out.should include number }
end

it "has access to thread local parallel_worker_number with 0 #{type}" do
type_key = "in_#{type}".to_sym
Parallel.map([1,2,3,4,5,6,7,8,9], type_key => 0) { |x| Thread.current[:parallel_worker_number] }.uniq.should == [0]
Thread.current[:parallel_worker_number].should be_nil
end
end

it "can run with 0 threads" do
Expand Down

0 comments on commit e576c6b

Please sign in to comment.