Created
September 20, 2023 12:09
-
-
Save andersonbosa/e27eef638f173c81d4d0b42a5a30b7f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/andersonbosa/e27eef638f173c81d4d0b42a5a30b7f2#file-thread_iterator-rb-L20
antes de processar poderia colocar em queue e ai deixa as threads lidar com a queue
Queue
é a única estrutura "thread-safe"