Skip to content

Commit fb9be71

Browse files
authored
Add clearer documentation for asynchronous I/O to the manual. (#35412)
This adds a section to the end of the "networking and streams" page that explicitly mentions asynchronous I/O and provides a couple of code examples using the @sync / @async macros. It uses a Sockets-based example for demonstrating the usage of the @sync / @async macros, since it does a better job of demonstrating the asynchronous nature of I/O functions.
1 parent 9559efc commit fb9be71

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

doc/src/manual/networking-and-streams.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,3 +312,42 @@ resolution:
312312
julia> getaddrinfo("google.com")
313313
ip"74.125.226.225"
314314
```
315+
316+
## Asynchronous I/O
317+
318+
319+
All I/O operations exposed by [`Base.read`](@ref) and [`Base.write`](@ref) can be performed
320+
asynchronously through the use of [coroutines](@ref man-tasks). You can create a new coroutine to
321+
read from or write to a stream using the [`@async`](@ref) macro:
322+
323+
```julia-repl
324+
julia> task = @async open("foo.txt", "w") do io
325+
write(io, "Hello, World!")
326+
end;
327+
328+
julia> wait(task)
329+
330+
julia> readlines("foo.txt")
331+
1-element Array{String,1}:
332+
"Hello, World!"
333+
```
334+
335+
It's common to run into situations where you want to perform multiple asynchronous operations
336+
concurrently and wait until they've all completed. You can use the [`@sync`](@ref) macro to cause
337+
your program to block until all of the coroutines it wraps around have exited:
338+
339+
```julia-repl
340+
julia> using Sockets
341+
342+
julia> @sync for hostname in ("google.com", "github.com", "julialang.org")
343+
@async begin
344+
conn = connect(hostname, 80)
345+
write(conn, "GET / HTTP/1.1\r\nHost:$(hostname)\r\n\r\n")
346+
readline(conn, keep=true)
347+
println("Finished connection to $(hostname)")
348+
end
349+
end
350+
Finished connection to google.com
351+
Finished connection to julialang.org
352+
Finished connection to github.com
353+
```

0 commit comments

Comments
 (0)