Mastering Tokio: Asynchronous Tasks and Runtime Management
This challenge focuses on understanding and utilizing the Tokio runtime in Rust for concurrent and asynchronous programming. You will learn how to spawn asynchronous tasks, manage their execution, and collect their results, which are fundamental skills for building high-performance network applications and other I/O-bound services.
Problem Description
Your task is to implement a Rust program that uses the Tokio runtime to execute multiple asynchronous tasks concurrently. These tasks will simulate performing some work and returning a value. You will need to:
- Initialize the Tokio Runtime: Create a Tokio runtime instance.
- Spawn Asynchronous Tasks: Define and spawn several asynchronous functions (tasks) onto the runtime. Each task should:
- Take an identifier (e.g., an integer) as input.
- Simulate some asynchronous work (e.g., using
tokio::time::sleep). - Return a
Stringthat includes its identifier and a confirmation message.
- Collect Task Results: Wait for all spawned tasks to complete and collect their returned
Stringvalues. - Output Results: Print the collected results in the order the tasks were initiated.
Examples
Example 1:
Input:
- Number of tasks: 3
- Task 1 performs work for 100ms
- Task 2 performs work for 50ms
- Task 3 performs work for 150ms
Output:
Task 1 completed: Result from task 1
Task 2 completed: Result from task 2
Task 3 completed: Result from task 3
Explanation: The program spawns three tasks. Task 2 finishes first, then Task 1, and finally Task 3. The output, however, is printed in the original order of task initiation, demonstrating that results are collected and presented in a deterministic sequence regardless of completion order. The content of each result string confirms the task's completion.
Example 2:
Input:
- Number of tasks: 1
- Task 1 performs work for 200ms
Output:
Task 1 completed: Result from task 1
Explanation: A single task is spawned and executed. Its result is collected and printed.
Example 3:
Input:
- Number of tasks: 0
Output:
No tasks were spawned.
Explanation: When no tasks are requested, the program should handle this gracefully by printing a message indicating that no tasks were executed.
Constraints
- The maximum number of tasks to spawn is 100.
- The maximum simulated work duration for any single task is 500 milliseconds.
- The program should be efficient and avoid unnecessary blocking operations.
- The output order of results must match the order in which tasks were spawned.
Notes
- You will need to add the
tokiodependency to yourCargo.tomlfile with thefullfeature enabled:tokio = { version = "1", features = ["full"] } - The
#[tokio::main]attribute is a convenient way to set up the Tokio runtime. - Consider using
tokio::spawnto initiate tasks andJoinHandleto manage their completion. - You might find
futures::future::join_allor similar combinators useful for waiting on multiple futures. - Remember that
tokio::time::sleepreturns aFuture.