T
tristin.colby
Newbie Question:
I have some code where I create 4 threads that pop elements off an
array and process them. The problem is that each thread only pops off
one element, processes it, then returns; they don't continue to
process until the entire array is consumed.
<code>
$jobs = %w[a b c d e f g]
def simulate_cleanup
puts "Checking for #{$jobs.length} jobs in /mnt/gen1/focal/temp"
threads = []
mu = Mutex.new
total = 0
1.upto(4) do |c|
threads << Thread.new do
puts "Thread #{c} created"
job = nil
mu.synchronize do
job = $jobs.pop
puts "Checking for #{job}"
#Exit our thread if we have no more jobs to check
puts "No more jobs" and return if job.nil?
end
t = count_files(job)
mu.synchronize { total += t }
end
end
threads.each { |t| t.join }
puts "Reduced by #{total} files"
end
Example of output:
Thread 1 created
Thread 2 created
Thread 3 created
Thread 4 created
Checking for a
Checking for b
Checking for c
Checking for d
I have some code where I create 4 threads that pop elements off an
array and process them. The problem is that each thread only pops off
one element, processes it, then returns; they don't continue to
process until the entire array is consumed.
<code>
$jobs = %w[a b c d e f g]
def simulate_cleanup
puts "Checking for #{$jobs.length} jobs in /mnt/gen1/focal/temp"
threads = []
mu = Mutex.new
total = 0
1.upto(4) do |c|
threads << Thread.new do
puts "Thread #{c} created"
job = nil
mu.synchronize do
job = $jobs.pop
puts "Checking for #{job}"
#Exit our thread if we have no more jobs to check
puts "No more jobs" and return if job.nil?
end
t = count_files(job)
mu.synchronize { total += t }
end
end
threads.each { |t| t.join }
puts "Reduced by #{total} files"
end
Example of output:
Thread 1 created
Thread 2 created
Thread 3 created
Thread 4 created
Checking for a
Checking for b
Checking for c
Checking for d