Both C# and Scala have adopted frameworks for simplifying doing asynchronous/parallel computation, but in different ways. The latest C# (5.0, still in beta) has decided on an async/await framework (using continuation-passing under the hood, but in an easier-to-use way), while Scala instead uses the concept of "actors", and has recently taken the actors implementation in Akka and incorporated it into the base library.
Here's a task to consider: We receive a series of requests to do various operations -- e.g. from user input, requests to a server, etc. Some operations are fast, but some take awhile. For the slow ones, we'd like to asynchronously do the operation (in another thread) and process it when the thread is done, while still being free to process new requests.
A simple synchronous loop might be (pseudo-code):
while (1) {
val request = waitForAnything(user_request, server_request)
val result = do_request(request)
if (result needs to be sent back)
send_back_result(result)
}
In a basic fork/join framework, you might do something like this (pseudo-code):
val threads: Set[Thread]
while (1) {
val request = waitForAnything(user_request, server_request, termination of thread)
if (request is thread_terminate) {
threads.delete(request.terminated_thread)
val result = request.thread_result
if (result needs to be sent back)
send_back_result(result)
} else if (request is slow) {
val thread = new Thread(() => do_request(request))
Threads.add(thread)
thread.start()
} else {
val result = do_request(request)
if (result needs to be sent back)
send_back_result(result)
}
}
How would this look expressed using async/await and using actors, and more generally what are the advantages/disadvantages of these approach?
Please consider mine as a partial answer: "old" Scala actors have been replaced by Akka actors , which are much more then a simple async/await library.
You can read more about Akka futures on the Akka website or on this post:
Parallel file processing in Scala
I can't speak for Scala, but the C# version would look something like this (I don't have an IDE handy so pardon any errors/typos:
public async Task<int> GetResult()
{
while (true)
{
var request = await waitForAnything(user_request, server_request);
var result = await do_request(request);
if (isValid(result))
return result;
}
}
And you would call it something like so:
public void RunTheProgram()
{
int result = await GetResult();
Console.WriteLine("Result: {0}", result);
}
In short, the actual code would look very much like the pseudo code, i.e. very much like how a normal human being would think about the problem. That's the real beauty of C#'s async/await.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With