lib/mutex_m.rb


DEFINITIONS

This source file includes following functions.


   1  #
   2  #   mutex_m.rb - 
   3  #       $Release Version: 3.0$
   4  #       $Revision: 1.7 $
   5  #       $Date: 1998/02/27 04:28:57 $
   6  #       Original from mutex.rb
   7  #       by Keiju ISHITSUKA(keiju@ishitsuka.com)
   8  #       modified by matz
   9  #       patched by akira yamada
  10  #
  11  # --
  12  #   Usage:
  13  #       require "mutex_m.rb"
  14  #       obj = Object.new
  15  #       obj.extend Mutex_m
  16  #       ...
  17  #       extended object can be handled like Mutex
  18  #       or
  19  #       class Foo
  20  #         include Mutex_m
  21  #         ...
  22  #       end
  23  #       obj = Foo.new
  24  #       this obj can be handled like Mutex
  25  #
  26  
  27  module Mutex_m
  28    def Mutex_m.define_aliases(cl)
  29      cl.module_eval %q{
  30        alias locked? mu_locked?
  31        alias lock mu_lock
  32        alias unlock mu_unlock
  33        alias try_lock mu_try_lock
  34        alias synchronize mu_synchronize
  35      }
  36    end  
  37  
  38    def Mutex_m.append_features(cl)
  39      super
  40      define_aliases(cl) unless cl.instance_of?(Module)
  41    end
  42    
  43    def Mutex_m.extend_object(obj)
  44      super
  45      obj.mu_extended
  46    end
  47  
  48    def mu_extended
  49      unless (defined? locked? and
  50              defined? lock and
  51              defined? unlock and
  52              defined? try_lock and
  53              defined? synchronize)
  54        Mutex_m.define_aliases(class<<self;self;end)
  55      end
  56      mu_initialize
  57    end
  58    
  59    # locking 
  60    def mu_synchronize
  61      begin
  62        mu_lock
  63        yield
  64      ensure
  65        mu_unlock
  66      end
  67    end
  68    
  69    def mu_locked?
  70      @mu_locked
  71    end
  72    
  73    def mu_try_lock
  74      result = false
  75      Thread.critical = true
  76      unless @mu_locked
  77        @mu_locked = true
  78        result = true
  79      end
  80      Thread.critical = false
  81      result
  82    end
  83    
  84    def mu_lock
  85      while (Thread.critical = true; @mu_locked)
  86        @mu_waiting.push Thread.current
  87        Thread.stop
  88      end
  89      @mu_locked = true
  90      Thread.critical = false
  91      self
  92    end
  93    
  94    def mu_unlock
  95      return unless @mu_locked
  96      Thread.critical = true
  97      wait = @mu_waiting
  98      @mu_waiting = []
  99      @mu_locked = false
 100      Thread.critical = false
 101      for w in wait
 102        w.run
 103      end
 104      self
 105    end
 106    
 107    private
 108    
 109    def mu_initialize
 110      @mu_waiting = []
 111      @mu_locked = false;
 112    end
 113  
 114    def initialize(*args)
 115      mu_initialize
 116      super
 117    end
 118  end