Sha256: a9a21ab6e4ce66f454c504295da6e6cfb79e004d5ef137e8088c63c97abdcf9c

Contents?: true

Size: 1.07 KB

Versions: 1

Compression:

Stored size: 1.07 KB

Contents

# encoding: utf-8

module FiniteMachine

  # A mixin to allow instance methods to be synchronized
  module Threadable
    module InstanceMethods
      @@sync = Sync.new

      def sync_exclusive(&block)
        @@sync.synchronize(:EX, &block)
      end

      def sync_shared(&block)
        @@sync.synchronize(:SH, &block)
      end
    end

    def self.included(base)
      base.extend ClassMethods
      base.module_eval do
        include InstanceMethods
      end
    end

    module ClassMethods
      include InstanceMethods

      def attr_threadsafe(*attrs)
        attrs.flatten.each do |attr|
          class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
            def #{attr}(*args)
              if args.empty?
                sync_shared { @#{attr} }
              else
                self.#{attr} = args.shift
              end
            end
            alias_method '#{attr}?', '#{attr}'

            def #{attr}=(value)
              sync_exclusive { @#{attr} = value }
            end
          RUBY_EVAL
        end
      end
    end

  end # Threadable
end # FiniteMachine

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
finite_machine-0.2.0 lib/finite_machine/threadable.rb