Class: Moneta::SynchronizePrimitive Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/moneta/synchronize.rb

Overview

This class is abstract.

Base class for Mutex and Semaphore

Direct Known Subclasses

Mutex, Semaphore

Instance Method Summary collapse

Instance Method Details

#enter(timeout = nil, wait = 0.01) ⇒ Boolean Also known as: lock

Enter critical section (blocking)

Parameters:

  • timeout (Number) (defaults to: nil)

    Maximum time to wait

  • wait (Number) (defaults to: 0.01)

    Sleep time between tries to acquire lock

Returns:

  • (Boolean)

    true if the lock was aquired



31
32
33
34
35
36
37
38
# File 'lib/moneta/synchronize.rb', line 31

def enter(timeout = nil, wait = 0.01)
  time_at_timeout = Time.now + timeout if timeout
  while !timeout || Time.now < time_at_timeout
    return true if try_enter
    sleep(wait)
  end
  false
end

#leaveObject Also known as: unlock

Leave critical section



42
43
44
45
46
47
# File 'lib/moneta/synchronize.rb', line 42

def leave
  raise 'Not locked' unless @locked
  leave_primitive
  @locked = false
  nil
end

#locked?Boolean

Is the lock acquired?

Returns:

  • (Boolean)


51
52
53
# File 'lib/moneta/synchronize.rb', line 51

def locked?
  @locked
end

#synchronize {|Synchronized| ... } ⇒ Object

Synchronize block

Yield Parameters:

  • Synchronized

    block

Returns:

  • (Object)

    result of block



10
11
12
13
14
15
# File 'lib/moneta/synchronize.rb', line 10

def synchronize
  enter
  yield
ensure
  leave
end

#try_enterBoolean Also known as: try_lock

Try to enter critical section (nonblocking)

Returns:

  • (Boolean)

    true if the lock was acquired



20
21
22
23
# File 'lib/moneta/synchronize.rb', line 20

def try_enter
  raise 'Already locked' if @locked
  enter_primitive ? @locked = true : false
end