Metered concurrency: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: Remove poor example. The other two are good. This one was a stretch.)
Line 1,277: Line 1,277:


Thread joining is automatic by default.
Thread joining is automatic by default.

=={{header|Ruby}}==

This one uses SizedQueue class from the standard library since it blocks when the size limit is reached. An alternative approach would be having a mutex and a counter and blocking explicitly.
<lang ruby>
require 'thread'

# Simple Semaphore implementation
class Semaphore
def initialize(size = 1)
@queue = SizedQueue.new(size)
size.times { acquire }
end

def acquire
tap { @queue.push(nil) }
end

def release
tap { @queue.pop }
end

# @return [Integer]
def count
@queue.length
end

def synchronize
release
yield
ensure
acquire
end
end

def foo(id, sem)
sem.synchronize do
puts "Thread #{id} Acquired lock"
sleep(2)
end
end

threads = []
n = 5
s = Semaphore.new(3)
n.times do |i|
threads << Thread.new { foo i, s }
end
threads.each(&:join)

</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==