require 'monitor' class CountingSemaphore def initialize(count) @count = count @monitor = Monitor.new @zero_cond = @monitor.new_cond end def synchronize @monitor.synchronize do @zero_cond.wait_while{ @count == 0 } @count -= 1 end ret = yield @monitor.synchronize do @count += 1 @zero_cond.broadcast end ret end end cs = CountingSemaphore.new(10) Array.new(100) do Thread.start do cs.synchronize{ `sle
![rubyでカウンティングセマフォ - Qiita](https://cdn-ak-scissors.b.st-hatena.com/image/square/8f9ef7b87831d09c97e75ccbf3b539b70d286d37/height=288;version=1;width=512/https%3A%2F%2Fqiita-user-contents.imgix.net%2Fhttps%253A%252F%252Fcdn.qiita.com%252Fassets%252Fpublic%252Farticle-ogp-background-412672c5f0600ab9a64263b751f1bc81.png%3Fixlib%3Drb-4.0.0%26w%3D1200%26mark64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZ3PTk3MiZoPTM3OCZ0eHQ9cnVieSVFMyU4MSVBNyVFMyU4MiVBQiVFMyU4MiVBNiVFMyU4MyVCMyVFMyU4MyU4NiVFMyU4MiVBMyVFMyU4MyVCMyVFMyU4MiVCMCVFMyU4MiVCQiVFMyU4MyU5RSVFMyU4MyU5NSVFMyU4MiVBOSZ0eHQtYWxpZ249bGVmdCUyQ3RvcCZ0eHQtY29sb3I9JTIzMjEyMTIxJnR4dC1mb250PUhpcmFnaW5vJTIwU2FucyUyMFc2JnR4dC1zaXplPTU2JnM9ZDA0MjVlNmU1MDk4OTAzYTIwZGZmNTM0ZTcxZmViZjc%26mark-x%3D142%26mark-y%3D57%26blend64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZoPTc2Jnc9NzcwJnR4dD0lNDBsb25nX2xvbmdfZmxvYXQmdHh0LWNvbG9yPSUyMzIxMjEyMSZ0eHQtZm9udD1IaXJhZ2lubyUyMFNhbnMlMjBXNiZ0eHQtc2l6ZT0zNiZ0eHQtYWxpZ249bGVmdCUyQ3RvcCZzPTYxMDk3ZGJjOTM5YTZhM2ZjNzlkOGFkODczOWU3NmQy%26blend-x%3D142%26blend-y%3D486%26blend-mode%3Dnormal%26s%3Da2c4cf4160a2b3693b8bafecd6079c35)