Skip to content

Instantly share code, notes, and snippets.

@dbreunig
Created June 7, 2024 15:48
Show Gist options
  • Save dbreunig/92dcc6eb8584cc78179a6998be47894a to your computer and use it in GitHub Desktop.
Save dbreunig/92dcc6eb8584cc78179a6998be47894a to your computer and use it in GitHub Desktop.
A simple demo for processing files using a Ractor pool
def process_file(filename)
puts "Processing file: #{filename}"
File.open(filename) do |filename|
# Do stuff
end
end
puts "Done processing file: #{filename}"
end
# Define the number of Ractors in the pool
POOL_SIZE = 10
# Create a pool of Ractors
ractors = POOL_SIZE.times.map do
Ractor.new do
loop do
filename = Ractor.receive
break if filename == :done
process_file(filename)
end
end
end
# Distribute the files among the Ractors in the pool
files = Dir.glob('*.json')
files.each_with_index do |file, index|
ractors[index % POOL_SIZE].send(file)
end
# Send the stop signal to each ractor to shut them down
ractors.each { |ractor| ractor.send(:done) }
# Wait for all Ractors to finish
ractors.each(&:take)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment