module IORequest::Utility::MultiThread

Adds some methods to spawn new threads and join them. @note This module creates instance variables with prefix +@multi_thread+.

Private Instance Methods

__multi_thread__mutex() click to toggle source

@return [Mutex] threads manipulations mutex.

# File lib/io_request/utility/multi_thread.rb, line 18
def __multi_thread__mutex
  @__multi_thread__mutex ||= Mutex.new
end
__multi_thread__remove_current_thread() click to toggle source

Removes current thread from thread list.

# File lib/io_request/utility/multi_thread.rb, line 41
def __multi_thread__remove_current_thread
  __multi_thread__mutex.synchronize do
    __multi_thread__threads.delete(Thread.current)
  end
end
__multi_thread__threads() click to toggle source

@return [Array<Thread>] array of running threads.

# File lib/io_request/utility/multi_thread.rb, line 12
def __multi_thread__threads
  @__multi_thread__threads ||= []
end
Also aliased as: running_threads
each_thread(&block) click to toggle source

For each running thread.

# File lib/io_request/utility/multi_thread.rb, line 48
def each_thread(&block)
  __multi_thread__threads.each(&block)
end
in_thread(*args, name: nil) { |*in_args| ... } click to toggle source

Runs block with provided arguments forwarded as arguments in separate thread. All the inline args will be passed to block. @param thread_name [String] thread name. @return [Thread]

# File lib/io_request/utility/multi_thread.rb, line 26
def in_thread(*args, name: nil)
  # Synchronizing addition/deletion of new threads. That's important
  __multi_thread__mutex.synchronize do
    new_thread = Thread.new(*args) do |*in_args|
      yield(*in_args)
    ensure
      __multi_thread__remove_current_thread
    end
    __multi_thread__threads << new_thread
    new_thread.name = name if name
    new_thread
  end
end
join_threads() click to toggle source

Joins each thread.

# File lib/io_request/utility/multi_thread.rb, line 59
def join_threads
  each_thread(&:join)
end
kill_threads() click to toggle source

Kills each thread.

# File lib/io_request/utility/multi_thread.rb, line 53
def kill_threads
  each_thread(&:kill)
  each_thread(&:join)
end
running_threads()