Module: Hammock::Mutex::InstanceMethods

Defined in:
lib/hammock/mutex.rb

Instance Method Summary collapse

Instance Method Details

#mutex(column, &block) ⇒ Object

Yield to the block after obtaining a column lock on self.

The column lock is obtained by trying to set the given column to the current time. Since the check is done within UPDATE conditions and not a separate SELECT, it is atomic.

After block returns, the column is reset to NULL, at which point the lock can be obtained by other calls to #mutex. The NULL update is done within an ensure block, so an exception within block won’t cause a stuck mutex.

Example:

@photo.mutex(:regenerating_thumbnails_at) { <some operation> }


28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/hammock/mutex.rb', line 28

def mutex column, &block
  L{
    sleep 1 and redo if self.class.update_all(
      ["#{connection.quote_column_name(column)} = ?", Time.now],
      ["#{connection.quote_column_name(self.class.primary_key)} = ? AND #{connection.quote_column_name(column)} IS NULL", id]
    ).zero?
    yield
  }.call
ensure
  self.class.update_all(
    ["#{connection.quote_column_name(column)} = ?", nil],
    ["#{connection.quote_column_name(self.class.primary_key)} = ?", id]
  )
end