Module: RbbtSemaphore
- Defined in:
- lib/rbbt/util/semaphore.rb
Constant Summary collapse
- SEM_MUTEX =
Mutex.new
Class Method Summary collapse
- .fork_each_on_semaphore(elems, size, file = nil) ⇒ Object
- .synchronize(sem) ⇒ Object
- .thread_each_on_semaphore(elems, size) ⇒ Object
- .with_semaphore(size, file = nil) ⇒ Object
Class Method Details
.fork_each_on_semaphore(elems, size, file = nil) ⇒ Object
84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/rbbt/util/semaphore.rb', line 84 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
57 58 59 60 61 62 63 64 65 |
# File 'lib/rbbt/util/semaphore.rb', line 57 def self.synchronize(sem) ret = RbbtSemaphore.wait_semaphore(sem) raise SemaphoreInterrupted if ret == -1 begin yield ensure RbbtSemaphore.post_semaphore(sem) end end |
.thread_each_on_semaphore(elems, size) ⇒ Object
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 142 143 144 145 |
# File 'lib/rbbt/util/semaphore.rb', line 98 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
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/rbbt/util/semaphore.rb', line 67 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.debug "Creating semaphore (#{ size }): #{file}" RbbtSemaphore.create_semaphore(file, size) yield file ensure Log.debug "Removing semaphore #{ file }" RbbtSemaphore.delete_semaphore(file) end end |