Rust Multi-Message Channel Communication
Write a Rust program that extends the previous program to send multiple messages through the channel and print them in the receiving thread.
Sample Solution:
Rust Code:
Output:
Received: Message 1 Received: Message 2 Received: Message 3 Received: Message 4 Received: Message 5
Explanation:
In the exercise above,
- Channel Creation:
- It creates a channel using "mpsc::channel()" from the "std::sync" module. This channel allows one-way communication between threads.
- Sender Thread:
- A new thread is spawned using "thread::spawn()". This thread sends multiple messages through the channel using a loop.
- Each message is a string formatted as "Message {i+1}".
- Receiver Thread:
- Another thread is spawned to receive and print messages from the channel.
- It also uses a loop to receive a fixed number of messages (defined by 'NUM_MESSAGES' constant).
- Each received message is printed to the console.
- Joining Threads:
- After spawning the sender and receiver threads, the main thread waits for both threads to complete their execution using "join()" method.
- This ensures that the program doesn't exit before both threads finish processing.
- Execution:
- When executed, the program will first spawn the sender and receiver threads concurrently.
- The sender thread sends messages through the channel, and the receiver thread receives and prints them.
- Finally, the main thread waits for both threads to finish before exiting.
Rust Code Editor:
Previous: Rust Thread Communication with Channels.
Next: Rust Multi-Sender, Single-Receiver Communication.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.