Module: Enumerable

Defined in:
lib/threadify.rb

Instance Method Summary collapse

Instance Method Details

#threadify(opts = {}, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/threadify.rb', line 19

def threadify opts = {}, &block
# setup
#
  opts = {:threads => opts} if Numeric === opts
  threads = Integer(opts[:threads] || opts['threads'] || Threadify.threads)
  done = Object.new.freeze
  nothing = done
  #jobs = Array.new(threads).map{ Queue.new }
  jobs = Array.new(threads).map{ [] }
  top = Thread.current

# produce jobs
#
  #producer = Thread.new do
    #this = Thread.current
    #this.abort_on_exception = Threadify.abort_on_exception

    each_with_index{|args, i| jobs[i % threads].push([args, i])}
    threads.times{|i| jobs[i].push(done)}
  #end

# setup consumer list
#
  consumers = Array.new threads 

# setup support for short-circuit bailout via 'throw :threadify'
#
  thrownv = Hash.new
  thrownq = Queue.new

  caught = false

  catcher = Thread.new do
    loop do
      thrown = thrownq.pop
      break if thrown == done
      i, thrown = thrown
      thrownv[i] = thrown
      caught = true
    end
  end

# fire off the consumers
#
  threads.times do |i|
    consumers[i] = Thread.new(jobs[i]) do |jobsi|
      this = Thread.current
      this.abort_on_exception = Threadify.abort_on_exception
  
      job = nil

      thrown =
        catch(:threadify) do
          loop{
            break if caught
            #job = jobsi.pop
            job = jobsi.shift
            break if job == done
            args = job.first
            jobsi << (job << block.call(*args))
          }
          nothing
        end


      unless nothing == thrown
        args, i = job
        thrownq.push [i, thrown]
      end
    end
  end

# wait for consumers to finish
#
  consumers.map{|t| t.join}

# nuke the catcher
#
  thrownq.push done
  catcher.join

# iff something(s) was thrown return the one which would have been thrown
# earliest in non-parallel execution
#
  unless thrownv.empty?
    key = thrownv.keys.sort.first
    return thrownv[key]
  end

# collect the results and return them
#
=begin
  jobs.push done
  ret = []
  while((job = jobs.pop) != done)
    elem, i, value = job
    ret[i] = value
  end
  ret
end
=end

  ret = []
  jobs.each do |results|
    results.each do |result|
      break if result == done
      elem, i, value = result
      ret[i] = value
    end
  end
  ret
end