Sha256: 13f963f93bf99ebbcf7ed592b41690c8dec46956de76792e345eda8692b49ef9

Contents?: true

Size: 1.54 KB

Versions: 16

Compression:

Stored size: 1.54 KB

Contents

# = Semaphore
#
# Technically a semaphore is simply an integer variable which
# has an execution queue associated with it.
#
# == Authors
#
# * Fukumoto
#
# = Copying
#
# 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.


# = 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

16 entries across 16 versions & 2 rubygems

Version Path
facets-2.8.4 lib/more/facets/semaphore.rb
facets-2.8.3 lib/more/facets/semaphore.rb
facets-2.8.2 lib/more/facets/semaphore.rb
facets-2.8.1 lib/more/facets/semaphore.rb
facets-2.8.0 lib/more/facets/semaphore.rb
facets-2.6.0 lib/more/facets/semaphore.rb
facets-2.4.0 lib/facets/semaphore.rb
facets-2.4.1 lib/facets/semaphore.rb
facets-2.4.4 lib/more/facets/semaphore.rb
facets-2.4.3 lib/more/facets/semaphore.rb
facets-2.4.2 lib/more/facets/semaphore.rb
facets-2.5.1 lib/more/facets/semaphore.rb
facets-2.4.5 lib/more/facets/semaphore.rb
facets-2.5.0 lib/more/facets/semaphore.rb
facets-2.5.2 lib/more/facets/semaphore.rb
mack-facets-0.8.2 lib/gems/facets-2.4.5/lib/more/facets/semaphore.rb