USING: help.markup help.syntax kernel quotations calendar ;\r
\r
HELP: semaphore\r
-{ $class-description "The class of counting semaphores." } ;\r
+{ $class-description "The class of counting semaphores. New instances can be created by calling " { $link <semaphore> } "." } ;\r
\r
HELP: <semaphore>\r
{ $values { "n" "a non-negative integer" } { "semaphore" semaphore } }\r
{ $values { "semaphore" semaphore } { "quot" quotation } }\r
{ $description "Calls the quotation with the semaphore held." } ;\r
\r
-ARTICLE: "concurrency.semaphores" "Counting semaphores"\r
-"Counting semaphores are used to ensure that no more than a fixed number of threads are executing in a critical section at a time; as such, they generalize " { $vocab-link "concurrency.locks" } ", since locks can be thought of as semaphores with an initial count of 1."\r
-$nl\r
+ARTICLE: "concurrency.semaphores.examples" "Semaphore examples"\r
"A use-case would be a batch processing server which runs a large number of jobs which perform calculations but then need to fire off expensive external processes or perform heavy network I/O. While for most of the time, the threads can all run in parallel, it might be desired that the expensive operation is not run by more than 10 threads at once, to avoid thrashing swap space or saturating the network. This can be accomplished with a counting semaphore:"\r
{ $code\r
"SYMBOL: expensive-section"\r
- "10 <semaphore> expensive-section set-global"\r
- "requests ["\r
+ "requests"\r
+ "10 <semaphore> '["\r
" ..."\r
- " expensive-section [ do-expensive-stuff ] with-semaphore"\r
+ " _ [ do-expensive-stuff ] with-semaphore"\r
" ..."\r
"] parallel-map"\r
}\r
+"Here is a concrete example which fetches content from 5 different web sites, making no more than 3 requests at a time:"\r
+{ $code\r
+ """USING: concurrency.combinators concurrency.semaphores\r
+fry http.client kernel urls ;\r
+\r
+{\r
+ URL" http://www.apple.com"\r
+ URL" http://www.google.com"\r
+ URL" http://www.ibm.com"\r
+ URL" http://www.hp.com"\r
+ URL" http://www.oracle.com"\r
+}\r
+2 <semaphore> '[\r
+ _ [\r
+ http-get nip\r
+ ] with-semaphore\r
+] parallel-map"""\r
+} ;\r
+\r
+ARTICLE: "concurrency.semaphores" "Counting semaphores"\r
+"Counting semaphores are used to ensure that no more than a fixed number of threads are executing in a critical section at a time; as such, they generalize " { $vocab-link "concurrency.locks" } ", since locks can be thought of as semaphores with an initial count of 1."\r
+{ $subsections "concurrency.semaphores.examples" }\r
"Creating semaphores:"\r
{ $subsections\r
semaphore\r