diff options
author | Eric Wong <normalperson@yhbt.net> | 2013-04-05 21:21:19 +0000 |
---|---|---|
committer | Eric Wong <normalperson@yhbt.net> | 2013-04-05 22:30:36 +0000 |
commit | 7f87cbc2e5289f328c3278a991519068d8747374 (patch) | |
tree | bcc48402f5231c4f03b6916affe9c0e0c3c95c20 /lib/mahoro/thread_safe.rb | |
parent | 803b2c842701ca74d504b61e8d35fd801e00c614 (diff) | |
download | mahoro-7f87cbc2e5289f328c3278a991519068d8747374.tar.gz |
add optional thread-safety module
This can make Mahoro easier-to-use in multi-threaded apps where magic concurrency is not required. For real concurrency, it is recommended users create per-thread Mahoro objects.
Diffstat (limited to 'lib/mahoro/thread_safe.rb')
-rw-r--r-- | lib/mahoro/thread_safe.rb | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/lib/mahoro/thread_safe.rb b/lib/mahoro/thread_safe.rb new file mode 100644 index 0000000..4e77c35 --- /dev/null +++ b/lib/mahoro/thread_safe.rb @@ -0,0 +1,45 @@ +require 'thread' + +# Adds thread-safety to an existing Mahoro object. +# +# magic_t cookies of libmagic are not thread-safe by default, +# thus Mahoro is not thread-safe by default, either. +# +# For applications using persistent thread pools, this module is NOT +# recommended. Instead, it is best to create thread-local instances +# of (non-thread-safe) Mahoro for best performance. +# +# This is only intended for applications using Mahoro which meet the +# following requirements: +# 1) uses short-lived threads +# 2) does not need high concurrency for Mahoro operations +# +# Usage example: +# require "mahoro/thread_safe" +# +# # create a Mahoro object as usual +# mahoro_obj = Mahoro.new(...) +# +# # enable thread-safety +# mahoro_obj.extend Mahoro::ThreadSafe +# +# # mahoro_obj may now be used by multiple threads with automatic +# # mutual exclusion (the following example is safe, but not concurrent). +# Thread.new { mahoro_obj.file("/path/to/some_file") } +# Thread.new { mahoro_obj.file("/path/to/some_other_file") } +# +# # Real concurrency must be achieved by using different Mahoro objects +# # in different threads. As of Mahoro v0.4, Mahoro releases the GVL +# # on (Matz) Ruby 1.9 and later. +module Mahoro::ThreadSafe + + def self.extended(obj) # :nodoc: + obj.instance_variable_set(:@lock, Mutex.new) + end + + eval( + %w(file buffer flags= valid? compile load).map do |meth| + "\ndef #{meth}(*args)\n @lock.synchronize { super }\nend\n" + end.join("") + ) +end |