mahoro.git  about / heads / tags
Ruby interface to libmagic
blob 4e77c3527e295ede2045fafa3c844e9deb43dbcc 1511 bytes (raw)
$ git show HEAD:lib/mahoro/thread_safe.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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

git clone https://yhbt.net/mahoro.git