diff --git a/crystal/concurrency.md b/crystal/concurrency.md new file mode 100644 index 000000000..f4ed916ac --- /dev/null +++ b/crystal/concurrency.md @@ -0,0 +1,17 @@ +# Concurrency +{id: concurrency} + +## Send and receive +{id: send-and-receive} +{i: Channel} +{i: send} +{i: receive} +{i: spawn} + +![](examples/concurrency/send_receive.cr) + +## Concurrent HTTP request +{id: concurrent-http-request} + +![](examples/concurrency/http_request.cr) + diff --git a/crystal/crystal.json b/crystal/crystal.json index 5a62a0c3d..451d15614 100755 --- a/crystal/crystal.json +++ b/crystal/crystal.json @@ -33,6 +33,7 @@ "time.md", "http_client.md", "process.md", + "concurrency.md", "other.md" ] } diff --git a/crystal/examples/concurrency/http_request.cr b/crystal/examples/concurrency/http_request.cr new file mode 100644 index 000000000..c1a147914 --- /dev/null +++ b/crystal/examples/concurrency/http_request.cr @@ -0,0 +1,15 @@ +require "http/client" +puts "before" +ch = Channel(HTTP::Client::Response).new + +puts "before spawn" +spawn do + puts "in spawn before send" + res = HTTP::Client.get "https://code-maven.com/" + ch.send res + puts "in spawn after send" +end + +puts "before receive" +res = ch.receive +puts "received #{res.body.size} bytes including this row: #{res.body.lines.select(//)}" diff --git a/crystal/examples/concurrency/send_receive.cr b/crystal/examples/concurrency/send_receive.cr new file mode 100644 index 000000000..108fcc4b4 --- /dev/null +++ b/crystal/examples/concurrency/send_receive.cr @@ -0,0 +1,13 @@ +puts "before" +ch = Channel(Int32).new + +puts "before spawn" +spawn do + puts "in spawn before send" + ch.send 42 + puts "in spawn after send" +end + +puts "before receive" +res = ch.receive +puts "received #{res}"