Class: Sync::SingleFlight::Call

Inherits:
Object
  • Object
show all
Defined in:
lib/sync/singleflight.rb

Instance Method Summary collapse

Constructor Details

#initializeCall

Returns a new instance of Call.



41
42
43
44
45
46
47
48
# File 'lib/sync/singleflight.rb', line 41

def initialize
  # Initialize synchronization primitives
  @lock = Mutex.new
  @finished = false
  @result = nil
  @exc = nil
  @condition = ConditionVariable.new
end

Instance Method Details

#awaitObject



61
62
63
64
65
66
67
68
69
70
# File 'lib/sync/singleflight.rb', line 61

def await
  @lock.synchronize do
    # Wait until the call is finished
    @condition.wait(@lock) until @finished
    # Raise the exception if one occurred
    raise @exc if @exc
    # Return the result
    @result
  end
end

#execObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/sync/singleflight.rb', line 72

def exec
  result = nil
  exc = nil
  begin
    # Execute the block and store the result
    result = yield
    result
  rescue => e
    # Capture any exception that occurs
    exc = e
    raise e
  ensure
    # Mark the call as finished with the result or exception
    finished(result, exc)
  end
end

#finished(result, exc) ⇒ Object



50
51
52
53
54
55
56
57
58
59
# File 'lib/sync/singleflight.rb', line 50

def finished(result, exc)
  @lock.synchronize do
    # Mark the call as finished and store the result or exception
    @finished = true
    @result = result
    @exc = exc
    # Notify all waiting threads
    @condition.broadcast
  end
end