Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Created September 20, 2023 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonbosa/e27eef638f173c81d4d0b42a5a30b7f2 to your computer and use it in GitHub Desktop.
Save andersonbosa/e27eef638f173c81d4d0b42a5a30b7f2 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# ThreadIterator is a class that allows iterating over an array in groups using threads.
class ThreadIterator
# Initialize the ThreadIterator with an array and a group size.
#
# @param array [Array] The array to iterate over.
# @param group_size [Integer] The size of each group.
def initialize(array, group_size)
@array = array
@group_size = group_size
@mutex = Mutex.new
end
# Iterate over the array in groups and execute a block for each group.
#
# @yieldparam group [Array] The current group being processed.
# @return [Array] The results from all threads.
def each_group(&block)
return enum_for(:each_group) unless block_given?
threads = []
results = []
# Iterate over the array in groups and spawn a thread for each group
@array.each_slice(@group_size) do |group|
threads << Thread.new do
result = block.call(group)
synchronize { results.concat(result) if result }
end
end
# Wait for all threads to finish
threads.each(&:join)
results
end
private
# Synchronize access to shared resources using the mutex
def synchronize(&block)
@mutex.synchronize(&block)
end
end
@andersonbosa
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment