Class: Wytch::Once

Inherits:
Object
  • Object
show all
Defined in:
lib/wytch/once.rb

Overview

A thread-safe utility for executing a block exactly once.

Once ensures that a given block of code is executed only one time, even when called from multiple threads. After the first execution, subsequent calls are no-ops.

Examples:

setup = Once.new { puts "Initializing..." }
setup.call  # prints "Initializing..."
setup.call  # does nothing
setup.call  # does nothing

Instance Method Summary collapse

Constructor Details

#initialize { ... } ⇒ Once

Creates a new Once instance with the given block.

Yields:

  • the block to execute once



19
20
21
22
# File 'lib/wytch/once.rb', line 19

def initialize(&block)
  @block = block
  @mutex = Mutex.new
end

Instance Method Details

#callvoid

This method returns an undefined value.

Executes the block if it hasn't been executed yet.

Thread-safe: if multiple threads call this simultaneously, only one will execute the block.



30
31
32
33
34
35
36
37
38
# File 'lib/wytch/once.rb', line 30

def call
  @mutex&.synchronize do
    return unless @mutex

    @block.call

    @mutex = nil
  end
end