Class: Wytch::Once
- Inherits:
-
Object
- Object
- Wytch::Once
- 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.
Instance Method Summary collapse
-
#call ⇒ void
Executes the block if it hasn't been executed yet.
-
#initialize { ... } ⇒ Once
constructor
Creates a new Once instance with the given block.
Constructor Details
#initialize { ... } ⇒ Once
Creates a new Once instance with the given block.
19 20 21 22 |
# File 'lib/wytch/once.rb', line 19 def initialize(&block) @block = block @mutex = Mutex.new end |
Instance Method Details
#call ⇒ void
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 |