How it works...

In this recipe, we discussed how to use the channel feature of Rust to send data of the type T, which implements the traits required for safely sending data across threads.

First, to start off with developing channels, we used the mpsc::channel() method to create a new channel; post this, we sent simple data, such as the thread_id, from the endpoints. The endpoints in our case were tx and rx, which were the transmitter and receiver endpoints of the channel. The channel now had two endpoints, namely Sender<T> and Receiver<T>, where T was the type of the message that had to be transferred.

In the first for loop, where our focus was on sending the data to the channel, we iterated with a variable named thread_id from 0 to the static NO_THREADS variable value. The sender endpoint is copied by the clone method and assigned to thread_id. Each thread sends its thread_no via the channel by spawning new threads in which the thread_id value is passed to the send(data).unwrap() methods. The thread takes ownership of the thread_tx value. Each thread queues a message in the channel, sending a non-blocking operation, and continues immediately after sending the message.

In the second for loop, all the messages are collected from the channel. We declare a vector named thread_holder with the capacity of the number of threads spawned, which is a prefixed static value called NO_THREADS. The recv method of rx collects the messages from the channel, and recv blocks the current thread if there are no messages available. All these messages are pushed to the thread_holder vector using the push method of the vector. In the last println statement, we showed the order in which the messages were sent by printing the thread_holder vector.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.249.198