Channels in Julia
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.
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.