Asynchronous Execution
Objectives: Create vector of data items to be processed. Spawn concurent coroutines, one for each data item. Collect and present results.
Python
from random import randint
import asyncio
N = 10
async def shift(x):
await asyncio.sleep(0.001 * randint(0, 10))
print(f"Done with {x}")
return 100 * x
async def launch():
tasks = [asyncio.create_task(shift(x)) for x in range(N)]
print("All spawned")
results = await asyncio.gather(*tasks)
print(f"Results: {results}")
asyncio.run(launch())
Rust
use std::time::Duration; use async_std::task; use futures::executor::block_on; use futures::future::join_all; use rand::Rng; const N: i32 = 10; async fn shift(x: i32) -> i32 { let ms = Duration::from_millis(1); let random = { let mut rng = rand::thread_rng(); rng.gen_range(0..10) }; task::sleep(random * ms).await; println!("Done with {}", x); return 100 * x; } async fn launch() { let tasks: Vec<_> = (0..N).map(|x| task::spawn(shift(x))).collect(); println!("All spawned"); let results = join_all(tasks).await; println!("Results: {:?}", results.iter().collect::<Vec<_>>()); } fn main() { block_on(launch()); }
Crystal
N = 10
def shift(x)
sleep(0.001 * rand(10))
puts "Done with #{x}"
100 * x
end
alias ResultChannel = Channel(Int32)
result_channels = [] of ResultChannel
N.times do |x|
result_channel = ResultChannel.new
result_channels << result_channel
spawn { result_channel.send(shift(x)) }
end
puts "All spawned"
results = result_channels.map &.receive
puts "Results: #{results}"