Module: RbbtSemaphore

Defined in:
lib/rbbt/util/semaphore.rb

Constant Summary collapse

SEM_MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.fork_each_on_semaphore(elems, size, file = nil) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/rbbt/util/semaphore.rb', line 80

def self.fork_each_on_semaphore(elems, size, file = nil)

  TSV.traverse elems, :cpus => size, :bar => "Fork each on semaphore: #{ Misc.fingerprint elems }", :into => Set.new do |elem|
    elems.annotate elem if elems.respond_to? :annotate
    begin
      yield elem
    rescue Interrupt
      Log.warn "Process #{Process.pid} was aborted"
    end
    nil
  end
  nil
end

.synchronize(sem) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/rbbt/util/semaphore.rb', line 54

def self.synchronize(sem)
  RbbtSemaphore.wait_semaphore(sem)
  begin
    yield
  ensure
    RbbtSemaphore.post_semaphore(sem)
  end
end

.thread_each_on_semaphore(elems, size) ⇒ Object



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
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/rbbt/util/semaphore.rb', line 94

def self.thread_each_on_semaphore(elems, size)
  mutex = Mutex.new
  count = 0
  cv = ConditionVariable.new
  wait_mutex = Mutex.new

  begin

    threads = []
    wait_mutex.synchronize do
      threads = elems.collect do |elem| 
        Thread.new(elem) do |elem|

          continue = false
          mutex.synchronize do
            while not continue do
              if count < size 
                continue = true
                count += 1
              end
              mutex.sleep 1 unless continue
            end
          end

          begin
            yield elem
          rescue Interrupt
            Log.error "Thread was aborted while processing: #{Misc.fingerprint elem}"
            raise $!
          ensure
            mutex.synchronize do
              count -= 1
              cv.signal if mutex.locked?
            end
          end
        end
      end
    end

    threads.each do |thread| 
      thread.join 
    end
  rescue Exception
    Log.exception $!
    Log.info "Ensuring threads are dead: #{threads.length}"
    threads.each do |thread| thread.kill end
  end
end

.with_semaphore(size, file = nil) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rbbt/util/semaphore.rb', line 63

def self.with_semaphore(size, file = nil)
  if file.nil?
    file = "/" << Misc.digest(rand(1000000000000).to_s) if file.nil?
  else
    file = file.gsub('/', '_') if file
  end

  begin
    Log.low "Creating semaphore (#{ size }): #{file}"
    RbbtSemaphore.create_semaphore(file, size)
    yield file
  ensure
    Log.low "Removing semaphore #{ file }"
    RbbtSemaphore.delete_semaphore(file)
  end
end