Sha256: 7836187563a193586d230e825b68aae788e4920bc75ddbdb51e717f221d8ea25

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

#--
# Semaphore
#
# Copyright (c) 2005 fukumoto
#
# Ruby License
#
# This module is free software. You may use, modify, and/or redistribute this
# software under the same terms as Ruby.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.
#
# ==========================================================================
#  Revision History
# ==========================================================================
#
#  2005.04.28 Trans  - Ported to Mega Modules
#
# ==========================================================================
#++

#:title: Semaphore (CountingSemaphore)
#
# Technically a semaphore is simply an integer variable which
# has an execution queue associated with it.
#
# == Usage
#
#   s = CountingSemaphore.new
#
#   TODO
#
# == Author(s)
#
# * fukumoto
#

class CountingSemaphore

  def initialize(initvalue = 0)
    @counter = initvalue
    @waiting_list = []
  end

  def wait
    Thread.critical = true
    if (@counter -= 1) < 0
      @waiting_list.push(Thread.current)
      Thread.stop
    end
    self
  ensure
    Thread.critical = false
  end

  def signal
    Thread.critical = true
    begin
      if (@counter += 1) <= 0
        t = @waiting_list.shift
        t.wakeup if t
      end
    rescue ThreadError
      retry
    end
    self
  ensure
    Thread.critical = false
  end

  alias_method( :down, :wait )
  alias_method( :up, :signal )
  alias_method( :p, :wait )
  alias_method( :v, :signal )

  def exclusive
    wait
    yield
  ensure
    signal
  end

  alias_method( :synchronize, :exclusive )

end

Semaphore = CountingSemaphore



#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#

# TODO

=begin #testing

  require 'test/unit'

=end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
facets-0.9.0 lib/mega/semaphore.rb