Asynchronous IO in Scala with futures

Use Futures in Scala 2.10. They were joint work between the Scala team, the Akka team, and Twitter to reach a more standardized future API and implementation for use across frameworks. We just published a guide at: http://docs.scala-lang.org/overviews/core/futures.html Beyond being completely non-blocking (by default, though we provide the ability to do managed blocking operations) and … Read more

How to configure a fine tuned thread pool for futures?

This answer is from monkjack, a comment from the accepted answer. However, one can miss this great answer so I’m reposting it here. implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10)) If you just need to change the thread pool count, just use the global executor and pass the following system properties. -Dscala.concurrent.context.numThreads=8 -Dscala.concurrent.context.maxThreads=8

How do I synchronously return a value calculated in an asynchronous Future?

Standard library futures Let’s use this as our minimal, reproducible example: async fn example() -> i32 { 42 } Call executor::block_on: use futures::executor; // 0.3.1 fn main() { let v = executor::block_on(example()); println!(“{}”, v); } Tokio Use the tokio::main attribute on any function (not just main!) to convert it from an asynchronous function to a … Read more

Why should I use std::async?

it’s called async, but it got a really “sequential behaviour”, No, if you use the std::launch::async policy then it runs asynchronously in a new thread. If you don’t specify a policy it might run in a new thread. basically in the row where you call the future associated with your async function foo, the program … Read more

How to use invokeAll() to let all thread pool do their task?

The way an ExecutorService works is that when you call invokeAll it waits for all tasks to complete: Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone() is true for each element of the returned list. Note that a completed task could have terminated either normally … Read more

Is there a way to cancel/detach a future in C++11?

The C++11 standard does not provide a direct way to cancel a task started with std::async. You will have to implement your own cancellation mechanism, such as passing in an atomic flag variable to the async task which is periodically checked. Your code should not crash though. On reaching the end of main, the std::future<int> … Read more

Combine awaitables like Promise.all

The equivalent would be using asyncio.gather: import asyncio async def bar(i): print(‘started’, i) await asyncio.sleep(1) print(‘finished’, i) async def main(): await asyncio.gather(*[bar(i) for i in range(10)]) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() Why doesn’t my approach work? Because when you await each item in seq, you block that coroutine. So in essence, you have synchronous code … Read more