Class: Tsafe::Proxy

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

Overview

Instances of this class proxies calls to a given-object by using a mutex or monitor.

Examples

threadsafe_array = Tsafe::Proxy.new(:obj => [])
threadsafe_array << 5
ret = threadsafe_array[0]

threadsafe_array = Tsafe::Proxy.new(:obj => [], :monitor => true)

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Proxy

Spawns needed vars.


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/tsafe_proxy.rb', line 11

def initialize(args)
  if args[:monitor]
    @mutex = Monitor.new
  elsif args[:mutex]
    @mutex = args[:mutex]
  else
    @mutex = Mutex.new
  end
  
  @obj = args[:obj]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Proxies all calls to this object through the mutex.


24
25
26
27
28
# File 'lib/tsafe_proxy.rb', line 24

def method_missing(method_name, *args, &block)
  @mutex.synchronize do
    @obj.__send__(method_name, *args, &block)
  end
end