Class: RecursiveMutex

Inherits:
Mutex
  • Object
show all
Defined in:
lib/thread/recursive_mutex.rb

Overview

A recursive mutex lets you lock in various threads recursively, allowing you to do multiple locks one inside another.

You really shouldn’t use this, but in some cases it makes your life easier.

Instance Method Summary collapse

Constructor Details

#initializeRecursiveMutex

Returns a new instance of RecursiveMutex.



18
19
20
21
22
23
# File 'lib/thread/recursive_mutex.rb', line 18

def initialize
	@threads_lock = Mutex.new
	@threads = Hash.new { |h, k| h[k] = 0 }

	super
end

Instance Method Details

#lockObject

Lock the mutex.



26
27
28
# File 'lib/thread/recursive_mutex.rb', line 26

def lock
	super if @threads_lock.synchronize{ (@threads[Thread.current] += 1) == 1 }
end

#unlockObject

Unlock the mutex.



31
32
33
34
35
36
37
# File 'lib/thread/recursive_mutex.rb', line 31

def unlock
	if @threads_lock.synchronize{ (@threads[Thread.current] -= 1) == 0 }
		@threads.delete(Thread.current)

		super
	end
end