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:



106
107
108
109
# File 'lib/cod/work_queue.rb', line 106

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.



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/cod/work_queue.rb', line 115

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