diff options
author | Eric Wong <normalperson@yhbt.net> | 2009-02-04 14:30:40 -0800 |
---|---|---|
committer | Eric Wong <normalperson@yhbt.net> | 2009-02-09 19:50:36 -0800 |
commit | 28d571b7cca709641d964e00e6004facb6bfcc7e (patch) | |
tree | ed260a408088db92adb190d2b9eddaa6be8ab580 /lib/unicorn/semaphore.rb | |
parent | 66254b6f2b0ebb3899413b12d96614ac9318daae (diff) | |
download | unicorn-28d571b7cca709641d964e00e6004facb6bfcc7e.tar.gz |
Avoid conflicting with existing Mongrel libraries since we'll be incompatible and break things w/o disrupting Mongrel installations.
Diffstat (limited to 'lib/unicorn/semaphore.rb')
-rw-r--r-- | lib/unicorn/semaphore.rb | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/lib/unicorn/semaphore.rb b/lib/unicorn/semaphore.rb new file mode 100644 index 0000000..1c0b87c --- /dev/null +++ b/lib/unicorn/semaphore.rb @@ -0,0 +1,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 |