Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript callback function on a separate thread

Javascript is single threaded. So does the callback function and it's containing function execute on the same thread as the main loop/event loop?

database.query("SELECT * FROM hugetable", function(rows) {  // anonymous callback function
   var result = rows;
   console.log(result.length);
});
console.log("I am going without waiting...");

If query() method and its callback function executes on the same thread as the event loop does then the blocking will occur. If not why Javascript is called single-threaded?

Can anyone help verify that javascript(browser/node.js) is using multiple threads behind the scene in order to achieve non-blocking?

Friends, I saw your comments and answers. Sorry I am very new to Javascript. I am confused in that single thread async call won't block. If there are 100 users request data from hugeTable which may take one minute each concurrently and the event loop dispatch these tasks in to a queue and execute them in turn how can the query() method execution not blocking the event loop since they are all on one single thread?

Brad answered this part.

like image 474
Shawn Avatar asked Dec 05 '13 03:12

Shawn


2 Answers

Node.js native libraries (not the JavaScript portions) use separate threads all the time, but all of the data for your code gets shuffled back to a single JavaScript execution thread.

It's impossible to tell you if other threads in the background are working on this query, since you didn't specify what DB library you're using. However, that doesn't matter as much as you think.

Let's suppose you were to create a thread for handling your database connection. You fire off a query, and that thread takes care of getting the query to the database server. Then what? That thread sits around doing absolutely nothing until there's data to come back. You've effectively wasted resources keeping a thread around that doesn't do a whole lot. Node.js doesn't work this way. You have one thread for JavaScript execution.

If you are sending or receiving data (which is mostly what your DB connector is going to do), then this is handled out of a background thread pool for you automatically. It's also possible whatever DB connector you're using has a native extension that can do whatever it wants with threads.

See my post here for a more full explanation: https://stackoverflow.com/a/19324665/362536

like image 60
Brad Avatar answered Nov 09 '22 05:11

Brad


Javascript is single threaded. So does the callback function and it's containing function execute on the same thread as the main loop/event loop?

Yes, you kind of answered your own question.

You are correct, JavaScript is single threaded. There is no other thread for a callback to execute on.

That said, external libraries written in C or C++ are free to spawn threads all they want.

like image 20
meagar Avatar answered Nov 09 '22 04:11

meagar