Channels in Julia

using Channels

function main()
    # Create a new channel. In Julia, channels are not typed.
    messages = Channel(1)

    # Send a value into a channel using the put! function.
    # Here we send "ping" to the messages channel we made above, from a new task.
    @async put!(messages, "ping")

    # The take! function receives a value from the channel.
    # Here we'll receive the "ping" message we sent above and print it out.
    msg = take!(messages)
    println(msg)
end

main()

In Julia, channels are the pipes that connect concurrent tasks. You can send values into channels from one task and receive those values into another task.

To create a new channel in Julia, we use the Channel() constructor. Unlike in some other languages, Julia channels are not typed by the values they convey.

To send a value into a channel, we use the put!() function. In this example, we send "ping" to the messages channel we created earlier, from a new asynchronous task created with the @async macro.

The take!() function receives a value from the channel. Here, we receive the "ping" message we sent above and print it out.

When we run the program, the "ping" message is successfully passed from one task to another via our channel.

$ julia channels.jl
ping

By default, put!() and take!() operations block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the "ping" message without having to use any other synchronization.

In Julia, the concept of goroutines is replaced by Tasks, which are similar in that they allow for concurrent execution. The @async macro is used to create and schedule a new task to run concurrently.