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



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

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

Instance Method Details

#exclusivelyObject



290
291
292
# File 'lib/osctld/lockable.rb', line 290

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

#inclusivelyObject



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

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

#init_lockObject



256
257
258
# File 'lib/osctld/lockable.rb', line 256

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

#lock(type) ⇒ Object



260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/osctld/lockable.rb', line 260

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

  when :exclusive, :rw
    @lock.acquire_exclusive

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

#unlock(type) ⇒ Object



273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/osctld/lockable.rb', line 273

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

  when :exclusive, :rw
    @lock.release_exclusive

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