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



244
245
246
# File 'lib/osctld/lockable.rb', line 244

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

Instance Method Details

#exclusivelyObject



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

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

#inclusivelyObject



278
279
280
# File 'lib/osctld/lockable.rb', line 278

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

#init_lockObject



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

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

#lock(type) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/osctld/lockable.rb', line 252

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



265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/osctld/lockable.rb', line 265

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