Class: Cod::ExclusiveSection

Inherits:
Object
  • Object
show all
Defined in:
lib/cod/work_queue.rb

Overview

A section of code that is entered only once. Instead of blocking threads that are waiting to enter, it just returns nil.

Instance Method Summary collapse

Constructor Details

#initializeExclusiveSection

:nodoc:



123
124
125
126
# File 'lib/cod/work_queue.rb', line 123

def initialize
  @mutex = Mutex.new
  @threads_in_block = 0
end

Instance Method Details

#enterObject

If no one is in the block given to #enter currently, this will yield to the block. If one thread is already executing that block, it will return nil.



132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/cod/work_queue.rb', line 132

def enter
  @mutex.synchronize { 
    return if @threads_in_block > 0
    @threads_in_block += 1 }
  begin
    yield
  ensure
    fail "Assert fails, #{@threads_in_block} threads in block" \
      if @threads_in_block != 1
    @mutex.synchronize { 
      @threads_in_block -= 1 }
  end
end