Module: ScoutSemaphore
- Defined in:
- lib/scout/semaphore.rb
Defined Under Namespace
Classes: SemaphoreInterrupted
Constant Summary
collapse
- SEM_MUTEX =
Mutex.new
Class Method Summary
collapse
Class Method Details
.fork_each_on_semaphore(elems, size, file = nil) ⇒ Object
93
94
95
96
97
98
99
100
101
102
103
104
105
|
# File 'lib/scout/semaphore.rb', line 93
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
.thread_each_on_semaphore(elems, size) ⇒ Object
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
146
147
148
149
150
151
152
153
154
|
# File 'lib/scout/semaphore.rb', line 107
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
# File 'lib/scout/semaphore.rb', line 76
def self.with_semaphore(size, file = nil)
if file.nil?
file = "/scout-" << Misc.digest(rand(100000000000).to_s)[0..10] if file.nil?
else
file = file.gsub('/', '_') if file
end
begin
Log.debug "Creating semaphore (#{ size }): #{file}"
ScoutSemaphore.create_semaphore(file, size)
yield file
ensure
Log.debug "Removing semaphore #{ file }"
ScoutSemaphore.delete_semaphore(file)
end
end
|