Class: Moneta::SynchronizePrimitive Private

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

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

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



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

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



46
47
48
49
50
51
# File 'lib/moneta/synchronize.rb', line 46

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

#locked?Boolean

Is the lock acquired?

Returns:

  • (Boolean)


57
58
59
# File 'lib/moneta/synchronize.rb', line 57

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



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

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