unicorn.git  about / heads / tags
Rack HTTP server for Unix and fast clients
blob 1c0b87cd1cd87066d38cbce17a81c728e5ad4980 822 bytes (raw)
$ git show v0.0.0:lib/mongrel/semaphore.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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
 
class Semaphore
  def initialize(resource_count = 0)
    @available_resource_count = resource_count
    @mutex = Mutex.new
    @waiting_threads = []
  end
  
  def wait
    make_thread_wait unless resource_is_available
  end
  
  def signal
    schedule_waiting_thread if thread_is_waiting
  end
  
  def synchronize
    self.wait
    yield
  ensure
    self.signal
  end
  
  private 
  
  def resource_is_available
    @mutex.synchronize do
      return (@available_resource_count -= 1) >= 0
    end
  end
  
  def make_thread_wait
    @waiting_threads << Thread.current
    Thread.stop  
  end
  
  def thread_is_waiting
    @mutex.synchronize do
      return (@available_resource_count += 1) <= 0
    end
  end
  
  def schedule_waiting_thread
    thread = @waiting_threads.shift
    thread.wakeup if thread
  end
end

git clone https://yhbt.net/unicorn.git