There is a lot of buzz about asyc await from the javascript world, the concept is very simple and make your code much more
readable.
You want to execute something without blocking the main thread but you want the next line of code to run once the non blocking code finish, meaning continue
code execution in its written order.
Ruby has a great concurrency gem which basically encapsulate low level threading and synchronization code
to common patterns like Future, Promise, Actor and much more.
I’d like to talk about concurrent-ruby async await feature, lets look at the following code.
The class Reporter knows to do 1 thing, report, it’ll sleep and print it’s thread id and a message
So if we’ll open an irb and call
And it’ll take a sec till you see output because of the sleep.
Now lets try the same with async
As you can see the method returns immediately without printing any value, it just returns a promise like object that will hold the result of report method once done.
To prove you that report in non blocking try this
As you can see the 1+1 returns before the reporters output
Now lets try the await method
This time code look like it run synchronously, but lets check the main thread id, as you can see the code run on
2 different threads but in sync. this is the actual power of await, sometimes we want to run something in a background thread,
and do something on another thread when done.
The purpose of the Concurrent::Async is to allow a class methods to be called in a synchronized
way, meaning the class will always be thread safe as long as you call it via async or await.
What actually happens in the backstage is whenever you use async/await the method invocation is inserted into a queue that got one worker thread that keep
this queue empty. because its just one thread that invoke the methods, it is safe for many threads to use the same object.
Around 2 years ago, I started a new management gig. it wasn’t the first, but it was the first with a relatively large team.
One of the most basic things I ne...
If you ever used any MVC framework, I’m sure you asked yourself more than once, ‘Where should I put this piece of code?’ (If not that’s also fine).
Well, the...
So I found out it’s not so documented, hopefully google will index this.
I have a page on my system that shows a google geo chart (same as this)
When clicki...
Comments