Skip to content
This repository was archived by the owner on Mar 15, 2022. It is now read-only.

Commit 5b467ea

Browse files
committed
Use Monitor in sync delegator, so methods can be reentrant.
1 parent ae81242 commit 5b467ea

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

lib/thread_safe/synchronized_delegator.rb

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
require 'delegate'
2+
require 'monitor'
23

34
# This class provides a trivial way to synchronize all calls to a given object
4-
# by wrapping it with a `Delegator` that performs `Mutex#lock/unlock` calls
5+
# by wrapping it with a `Delegator` that performs `Monitor#enter/exit` calls
56
# around the delegated `#send`. Example:
67
#
78
# array = [] # not thread-safe on many impls
89
# array = SynchronizedDelegator.new([]) # thread-safe
910
#
10-
# A simple `Mutex` provides a very coarse-grained way to synchronize a given
11+
# A simple `Monitor` provides a very coarse-grained way to synchronize a given
1112
# object, in that it will cause synchronization for methods that have no
1213
# need for it, but this is a trivial way to get thread-safety where none may
1314
# exist currently on some implementations.
@@ -18,33 +19,33 @@ class SynchronizedDelegator < SimpleDelegator
1819

1920
def initialize(obj)
2021
__setobj__(obj)
21-
@mutex = Mutex.new
22+
@monitor = Monitor.new
2223
end
2324

2425
def method_missing(method, *args, &block)
25-
mutex = @mutex
26+
monitor = @monitor
2627
begin
27-
mutex.lock
28+
monitor.enter
2829
super
2930
ensure
30-
mutex.unlock
31+
monitor.exit
3132
end
3233
end
3334

3435
# Work-around for 1.8 std-lib not passing block around to delegate.
3536
# @private
3637
def method_missing(method, *args, &block)
37-
mutex = @mutex
38+
monitor = @monitor
3839
begin
39-
mutex.lock
40+
monitor.enter
4041
target = self.__getobj__
4142
if target.respond_to?(method)
4243
target.__send__(method, *args, &block)
4344
else
4445
super(method, *args, &block)
4546
end
4647
ensure
47-
mutex.unlock
48+
monitor.exit
4849
end
4950
end if RUBY_VERSION[0, 3] == '1.8'
5051

0 commit comments

Comments
 (0)