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
41
# File 'lib/moneta/synchronize.rb', line 33

def enter(timeout = nil, wait = 0.01)
  total = 0
  while !timeout || total < timeout
    return true if try_enter
    sleep(wait)
    total += wait
  end
  false
end

#leaveObject Also known as: unlock

Leave critical section



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

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

#locked?Boolean

Is the lock acquired?

Returns:

  • (Boolean)


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

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