Sha256: 1eef0ff49573a365d74200302808af429ea2ea4cb3c9c8e57c3a9bb5c5b3e7e5

Contents?: true

Size: 1.6 KB

Versions: 13

Compression:

Stored size: 1.6 KB

Contents

# TITLE:
#
#   Semaphore
#
# SUMMARY:
#
#   Technically a semaphore is simply an integer variable which
#   has an execution queue associated with it.
#
# COPYRIGHT:
#
#   Copyright (c) 2005 Fukumoto
#
# LICENSE:
#
#   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.
#
# AUTHORS:
#
#   - Fukumoto


# = Semaphore
#
# Technically a semaphore is simply an integer variable which
# has an execution queue associated with it.
class Semaphore

  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


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

# TODO

=begin #test

  require 'test/unit'

=end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
facets-2.0.0 lib/more/facets/semaphore.rb
facets-2.0.1 lib/more/facets/semaphore.rb
facets-2.0.2 lib/more/facets/semaphore.rb
facets-2.0.4 lib/more/facets/semaphore.rb
facets-2.0.5 lib/more/facets/semaphore.rb
facets-2.1.1 lib/more/facets/semaphore.rb
facets-2.1.2 lib/more/facets/semaphore.rb
facets-2.1.0 lib/more/facets/semaphore.rb
facets-2.0.3 lib/more/facets/semaphore.rb
facets-2.1.3 lib/more/facets/semaphore.rb
facets-2.2.0 lib/more/facets/semaphore.rb
facets-2.2.1 lib/more/facets/semaphore.rb
facets-2.3.0 lib/class/facets/semaphore.rb