Class: SzymanskisMutex

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

Overview

Based on the Szymanski’s Mutual Exclusion Algorithm

Constant Summary collapse

SZYMANSKIS_SLEEP =

Larger seconds mean less cycles/second but may result in lower completion

0.05
@@flags =
{}
@@counter =
{}

Class Method Summary collapse

Class Method Details

.mutual_exclusion(concern) ⇒ Object

Provide a MutEx lock Provide the critical section as a block to this method Different concerns will prevent unrelated code to wait on each other Returns the result of the critical code or nil if something fails



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/szymanskis_mutex.rb', line 41

def mutual_exclusion(concern)
  @@counter[concern] ||= 0
  @@flags[concern] ||= {}

  # Suppose @@counter += 1 is an atomic function
  my_id = @@counter[concern] += 1

  entry_protocol(concern, my_id)
  begin
    result = yield
  ensure
    # If something fails in the critical section release the resource
    exit_protocol(concern, my_id)
    result
  end
end