Class: VinaryTree::Liblevenshtein::ConcurrentHandle

Inherits:
Object
  • Object
show all
Defined in:
lib/vinary_tree/liblevenshtein.rb

Overview

A lifetime gate that permits concurrent native calls and only coordinates close with in-flight operations. It never serializes ordinary reads.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pointer, releaser) ⇒ ConcurrentHandle

Returns a new instance of ConcurrentHandle.



52
53
54
55
56
57
58
59
# File 'lib/vinary_tree/liblevenshtein.rb', line 52

def initialize(pointer, releaser)
  @pointer = pointer
  @releaser = releaser
  @active = 0
  @closing = false
  @mutex = Mutex.new
  @condition = ConditionVariable.new
end

Class Method Details

.finalizer(handle) ⇒ Object



88
# File 'lib/vinary_tree/liblevenshtein.rb', line 88

def self.finalizer(handle) = proc { handle.close rescue nil }

Instance Method Details

#closeObject



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/vinary_tree/liblevenshtein.rb', line 75

def close
  pointer = @mutex.synchronize do
    return 0 if @pointer.zero?
    @closing = true
    @condition.wait(@mutex) until @active.zero?
    result = @pointer
    @pointer = 0
    result
  end
  @releaser.call(pointer) unless pointer.zero?
  pointer
end

#with_pointerObject



61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/vinary_tree/liblevenshtein.rb', line 61

def with_pointer
  pointer = @mutex.synchronize do
    raise IOError, "native handle is closed" if @closing || @pointer.zero?
    @active += 1
    @pointer
  end
  yield pointer
ensure
  @mutex.synchronize do
    @active -= 1
    @condition.broadcast if @active.zero?
  end if pointer
end