Module: Archipelago::Current::ThreadedCollection

Included in:
Disco::ServiceLocker
Defined in:
lib/archipelago/current.rb

Overview

Adds a few threaded methods to the normal ruby collections.

The only method your class has to implement to use this module is each(&block).

NB: Will work slightly different than the unthreaded ones in certain circumstances.

Instance Method Summary collapse

Instance Method Details

#t_collect(callable = nil, &block) ⇒ Object

Like collect, except calls block or callable within a new thread.



67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/archipelago/current.rb', line 67

def t_collect(callable = nil, &block)
  raise "You have to provide either callable or block" if callable.nil? && block.nil?

  result = []
  result.extend(Synchronized)
  self.t_each do |args|
    new_value = call_helper(callable, args, &block)
    result.synchronize do
      result << new_value
    end
  end
  return result
end

#t_each(callable = nil, &block) ⇒ Object

Like each, except calls block or callable within a new thread.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/archipelago/current.rb', line 48

def t_each(callable = nil, &block)
  raise "You have to provide either callable or block" if callable.nil? && block.nil?

  threads = []

  self.each do |args|
    threads << Thread.new do
      call_helper(callable, args, &block)
    end
  end

  threads.each do |thread|
    thread.join
  end
end

#t_reject(callable = nil, &block) ⇒ Object

Like reject, except calls block or callable within a new thread.



101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/archipelago/current.rb', line 101

def t_reject(callable = nil, &block)
  raise "You have to provide either callable or block" if callable.nil? && block.nil?
  
  result = []
  result.extend(Synchronized)
  self.t_each do |args|
    matches = call_helper(callable, args, &block)
    result.synchronize do
      result << args
    end unless matches
  end
  return result
end

#t_select(callable = nil, &block) ⇒ Object

Like select, except calls block or callable within a new thread.



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/archipelago/current.rb', line 84

def t_select(callable = nil, &block)
  raise "You have to provide either callable or block" if callable.nil? && block.nil?

  result = []
  result.extend(Synchronized)
  self.t_each do |args|
    matches = call_helper(callable, args, &block)
    result.synchronize do
      result << args
    end if matches
  end
  return result
end