Metered concurrency: Difference between revisions
Content added Content deleted
m (→{{header|Perl 6}}: spelling) |
(→{{header|Groovy}}: new solution) |
||
Line 733: | Line 733: | ||
studied.Done() // signal done |
studied.Done() // signal done |
||
}</lang> |
}</lang> |
||
=={{header|Groovy}}== |
|||
Solution: |
|||
<lang groovy>class CountingSemaphore { |
|||
private int count = 0 |
|||
private final int max |
|||
CountingSemaphore(int max) { this.max = max } |
|||
synchronized int acquire() { |
|||
while (count >= max) { wait() } |
|||
++count |
|||
} |
|||
synchronized int release() { |
|||
if (count) { count--; notifyAll() } |
|||
count |
|||
} |
|||
synchronized int getCount() { count } |
|||
}</lang> |
|||
Test: |
|||
<lang groovy>def cs = new CountingSemaphore(4) |
|||
(1..12).each { threadID -> |
|||
Thread.start { |
|||
def id = "Thread #${(threadID as String).padLeft(2,'0')}" |
|||
try { |
|||
def sCount = cs.acquire() |
|||
println("${id} has acquired Semaphore at count = ${sCount}") |
|||
sleep(2000) |
|||
} finally { |
|||
println("${id} is releasing Semaphore at count = ${cs.count}") |
|||
cs.release() |
|||
} |
|||
} |
|||
}</lang> |
|||
Output: |
|||
<pre style="height:30ex;overflow:scroll;">Thread #03 has acquired Semaphore at count = 4 |
|||
Thread #07 has acquired Semaphore at count = 2 |
|||
Thread #02 has acquired Semaphore at count = 1 |
|||
Thread #09 has acquired Semaphore at count = 3 |
|||
Thread #03 is releasing Semaphore at count = 4 |
|||
Thread #02 is releasing Semaphore at count = 4 |
|||
Thread #09 is releasing Semaphore at count = 4 |
|||
Thread #07 is releasing Semaphore at count = 4 |
|||
Thread #12 has acquired Semaphore at count = 4 |
|||
Thread #05 has acquired Semaphore at count = 3 |
|||
Thread #06 has acquired Semaphore at count = 4 |
|||
Thread #08 has acquired Semaphore at count = 2 |
|||
Thread #12 is releasing Semaphore at count = 4 |
|||
Thread #06 is releasing Semaphore at count = 4 |
|||
Thread #05 is releasing Semaphore at count = 4 |
|||
Thread #10 has acquired Semaphore at count = 4 |
|||
Thread #11 has acquired Semaphore at count = 4 |
|||
Thread #08 is releasing Semaphore at count = 3 |
|||
Thread #01 has acquired Semaphore at count = 4 |
|||
Thread #04 has acquired Semaphore at count = 4 |
|||
Thread #11 is releasing Semaphore at count = 4 |
|||
Thread #10 is releasing Semaphore at count = 4 |
|||
Thread #04 is releasing Semaphore at count = 2 |
|||
Thread #01 is releasing Semaphore at count = 2</pre> |
|||
=={{header|Haskell}}== |
=={{header|Haskell}}== |