Module: OsCtld::Lockable

Overview

This module adds support for inclusive/exclusive object locking.

Lockable should be used for synchronization of osctld state. The locks should be held only for a short time to read/modify the state. Use Manipulable for long operations that require locking. Ideally, the included methods should be treated as protected, i.e. should not be used from the outside.

If the thread waits for Lock::TIMEOUT seconds to acquire the lock, an exception is raised.

Multiple threads can hold inclusive locks at the same time, but only one thread can hold an exclusive one. When a thread has acquired an exclusive lock, no other thread can get inclusive, nor exclusive lock.

Before the locks can be used, `init_lock()` has to be called. Locks can then be acquired using `lock()` and released using `unlock()`. You can also use `inclusively()` and `exclusively()` to execute a block within the lock.

Lockable provides helpers for synchronized alternatives to `attr_reader`, `attr_writer` and `attr_accessor`:

attr_inclusive_reader :attr1, :attr2, ...
attr_exclusive_writer :attr1, :attr2, ...
attr_synchronized_accessor :attr1, :attr2, ...

Defined Under Namespace

Modules: ClassMethods Classes: Lock

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



247
248
249
# File 'lib/osctld/lockable.rb', line 247

def self.included(klass)
  klass.extend(ClassMethods)
end

Instance Method Details

#exclusively(&block) ⇒ Object



285
286
287
# File 'lib/osctld/lockable.rb', line 285

def exclusively(&block)
  @lock.exclusively(&block)
end

#inclusively(&block) ⇒ Object



281
282
283
# File 'lib/osctld/lockable.rb', line 281

def inclusively(&block)
  @lock.inclusively(&block)
end

#init_lockObject



251
252
253
# File 'lib/osctld/lockable.rb', line 251

def init_lock
  @lock = Lock.new(self)
end

#lock(type) ⇒ Object



255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/osctld/lockable.rb', line 255

def lock(type)
  case type
  when :inclusive, :ro
    @lock.acquire_inclusive

  when :exclusive, :rw
    @lock.acquire_exclusive

  else
    fail "unknown lock type '#{type}'"
  end
end

#unlock(type) ⇒ Object



268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/osctld/lockable.rb', line 268

def unlock(type)
  case type
  when :inclusive, :ro
    @lock.release_inclusive

  when :exclusive, :rw
    @lock.release_exclusive

  else
    fail "unknown lock type '#{type}'"
  end
end