Created
December 29, 2010 02:51
-
-
Save anekos/758098 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
require "thread" | |
class Semaphore | |
def initialize (limit) | |
@mutex = Mutex.new | |
@count = limit | |
end | |
def enter | |
sleep(0.1) until @mutex.synchronize { @count > 0 and @count -= 1 } | |
end | |
def leave | |
@mutex.synchronize { @count += 1 } | |
end | |
end | |
def hoge(data) | |
# うまくいってるか、分かりやすくするためにランダム時間待つ | |
w = 3 + (rand * 5).to_i | |
puts("[#{data}] begin (wait #{w} sec)") | |
sleep(w) | |
puts("[#{data}] end") | |
end | |
# 最大3スレッドまで実行 | |
sem = Semaphore.new(3) | |
(1..10).to_a.each do | |
|alpha| | |
sem.enter | |
Thread.new(alpha) do | |
|alpha| | |
begin | |
hoge(alpha) | |
ensure | |
sem.leave | |
end | |
end | |
end | |
sleep 1 while Thread.list.size > 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment