Method to get the running thread id in javascript/jquery - javascript

I am new to javascript/jquery.
I have a simple question one of java script function is running and wanted to see the thread id for that thread.
In java we do like
Thread.getID();//in java
which will print the thread id of running thread.
In the similar way what is the function we use to get the running thread id in javscript.
Actually what i want is..
In my JavaScript, I have a listener which is listening to the channel. When ever there is a message in the channel, the callback method is called and processes the data. So here I am trying to see how it works in that way.. Let's say there are 10 messages in the channel and for each message the callback is called.
Let's say the callback method is running for a message "a" and while processing the data for the message "a", it got another message "b". Will the callback method for "b" be called once the processing for message "a" is complete?
I wanted to check this by printing the thread number in the callback function which tells whether it is running sequentially (one thread) or multiple threads. That is why I was trying to print the thread id. Thanks for your responses.
Thanks,
Swati

JavaScript is single threaded. So this wouldn't apply to JavaScript.
However, it is possible to spawn multiple threads through a very limited Worker interface introduced in HTML5 and is already available on some browsers. From an MDC article,
The Worker interface spawns real OS-level threads, and concurrency can cause interesting effects in your code if you aren't careful. However, in the case of web workers, the carefully controlled communication points with other threads means that it's actually very hard to cause concurrency problems. There's no access to non-thread safe components or the DOM and you have to pass specific data in and out of a thread through serialized objects. So you have to work really hard to cause problems in your code.
What do you need this for?

For most things in JavaScript there's one thread, so there's no method for this, since it'd invariable by "1" where you could access such information. There are more threads in the background for events and queuing (handled by the browser), but as far as your code's concerned, there's a main thread.
Java != JavaScript, they only share 4 letters :)

Aside from the name, Javascript is totally unrelated to Java. Javascript does not have threads that you can access.

In javascript the scripts run in a browser thread, and your code have no access to that info, actually your code have no idea whatsoever how it's being run. So NO! there's no such thing in javascript.

Related

Java Script is a single threded then how it can have fetch or other libraries to make async request

We can make Fetch or any other Async request with JavaScript, But Java script is itself a single threaded quite confusing
Javascript runs on a core which is single threaded and its also a event driven language that make all request into events,
application running in node js runs asynchronously using node event loop and event loop where looks upon the events and process them asynchronously.
So the request you make taken by events and processed asynchronously.
You're confusing asynchronous programming with multi threaded programming. See this answer: Does async programming mean multi-threading?
The trick is that the browser / nodejs instance has other threads for network handling, file reading etc. So it actually is multithreaded, but you dont need to deal with that as js opens these threads for you in the background. You just work with promises and callbacks to get the results out of these threads.
Browser eventLoop:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
A very interesting property of the event loop model is that JavaScript, unlike a lot of other languages, never blocks. 
Refer this content - receiving-results-asynchronously

C++ callbacks are not called for Node bindings

I'm stuck. It is the first time I use Node.js and javascript. I was trying to implement Node.js bindings for a library written in C++. I wrote them and tested with a simple console example and they worked. However, when I use http server, callbacks from the library are not called.
Let me explain step by step. The library receives HID messages from devices, asynchronously. Callbacks are called in the main thread. There should be an event loop which allows to receive those messages. So for Mac OS, I simply do
CFRunLoopRunInMode(kCFRunLoopDefaultMode, milliseconds/1000.0, false) ;
in a while loop to simulate the event loop in C++. When I wrote bindings with Nan, I thought I don't need this part of code because Node's event loop will take of that for me (when I simply run the server). However, the C++ callbacks are not called.
If I add a binding to run the CFRunLoopRunInMode, I receive HID messages as I want, but the main thread is blocked and the server is not working.
Then I tried putting setInterval/setImmediate/setTimeout/nextTick and calling the CFRunLoopRunInMode there. It works for about a hundred callbacks (HID messages) and then I do not receive C++ callbacks again.
I think, I need something that manages C++ callbacks without blocking the main thread. Hope I explained clear enough and sorry if I did mistakes with terminology/technical details.

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.
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
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.
Good question, javaScript is single-threaded yet asynchronous, that means for each asynchronous call it will perform a small pause on the main thread to execute the callback, at least that's for browsers and even there you will have web-workers that will spawn a new thread per worker.
What you're doing in your code is deferring the evaluation of the query (execution of the callback) until after the query has run and rows have been retrieved.
In modern browsers you can create two threads if desired using webworkers.
Node.js is a seperate story - you can create child processes which will run on a seperate thread when desired. See this post for further information.

Since JavaScript is single-threaded, how are web workers in HTML5 doing multi-threading?

I've been reading about web workers in HTML5, but I know JavaScript is single-threaded.
How are web workers doing multi-threaded work then? or how are they simulating it if it's not truly multi-threaded?
As several comments have already pointed out, Workers really are multi-threaded.
Some points which may help clarify your thinking:
JavaScript is a language, it doesn't define a threading model, it's not necessarily single threaded
Most browsers have historically been single threaded (though that is changing rapidly: IE, Chrome, Firefox), and most JavaScript implementations occur in browsers
Web Workers are not part of JavaScript, they are a browser feature which can be accessed through JavaScript
A bit late, but I just asked myself the same question and I came up with the following answer:
Javascript in browsers is always single-threaded, and a fundamental consequence is that "concurrent" access to variables (the principal headache of multithreaded programming) is actually not concurrent; this is true with the exception of webworkers, which are actually run in separate threads and concurrent access to variables must be dealt with in a somewhat explicit way.
I am not a JavaScript ninja, but I too was convinced that JavaScript in browser is provided as a single threaded process, without paying much attention to whether it was true or to the rationale behind this belief.
A simple fact that supports this assumption is that when programming in JavaScript you don't have to care about concurrent access to shared variables. Every developer, without even thinking of the problem, writes code as if every access to a variable is consistent.
In other words, you don't need to worry about the so called Memory model.
Actually there is no need of looking at WebWorkers to involve parallel processing in JavaScript. Think of an (asynchronous) AJAX request. And think how carelessly you would handle concurrent access to variables:
var counter = 0;
function asyncAddCounter() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
counter++;
}
};
xhttp.open("GET", "/a/remote/resource", true);
xhttp.send();
}
asyncAddCounter();
counter++;
What is the value of counter at the end of the process? It is 2.
It doesn't matter that it is read and written "concurrently", it will never result in a 1. This means that access to counter is always consistent.
If two threads where really accessing the value concurrently, they both could start off by reading 0 and both write 1 in the end.
In browsers, the actual data-fetching of a remote resource is hidden to the developer, and its inner workings are outside the scope of the JavaScript API (what the browser let's you control in terms of JavaScript instructions). As far as the developer is concerned, the result of the network request is processed by the main thread.
In short, the actual carrying out of the request is not visible, but the invocation of the callback (handling the result by custom JavaScript code) is executed by the main thread.
Possibly, if it wasn't for the webworkers, the term "multithreading" wouldn't ever enter the Javascript world.
The execution of the request and the asynchronous invocation of the callback is actually achieved by using event loops, not multithreading. This is true for several browsers and obviously for Node.js. The following are some references, in some cases a bit obsolete, but I guess that the main idea is still retained nowadays.
Firefox: Concurrency model and Event Loop - JavaScript | MDN
Chrome uses libevent in certain OS.
IE: Understanding the Event Model (Internet Explorer)
This fact is the reason why JavaScript is said to be Event-driven but not multithreaded.
Notice that JavaScript thus allows for asynchronous idioms, but not parallel execution of JavaScript code (outside webworkers). The term asynchronous just denotes the fact that the result of two instructions might be processed in scrambled order.
As for WebWorkers, they are JavaScript APIs that give a developer control over a multithreaded process.
As such, they provide explicit ways to handle concurrent access to shared memory (read and write values in different threads), and this is done, among the others, in the following ways:
you push data to a web worker (which means that the new thread reads data) by structured clone: The structured clone algorithm - Web APIs | MDN. Essentially there is no "shared" variable, instead the new thread is given a fresh copy of the object.
you push data to a web worker by transferring ownership of the value: Transferable - Web APIs | MDN. This means that the just one thread can read its value at any time.
as for the results returned by the web workers (how they "write"), the main thread access the results when prompted to do so (for instance with the instruction thisWorker.onmessage = function(e) {console.log('Message ' + e.data + ' received from worker');}). It must be by means of the usual Event Loop, I must suppose.
the main thread and the web worker access a truly shared memory, the SharedArrayBuffer, which is thread-safely accessed using the Atomic functions. I found this clearly exposed in this article: JavaScript: From Workers to Shared Memory
note: webworkers cannot access the DOM, which is truly shared!
You spawn a .js file as a "worker", and it runs processes in a separate thread. You can pass JSON data back and forth between it and the "main" thread. Workers don't have access to certain things like the DOM, though.
So if, say, you wanted to solve complicated math problems, you could let the user enter things into the browser, pass those variables off to the worker, let it do the computation in the background while in the main thread you let the user do other things, or show a progress bar or something, and then when the worker's done, it passes the answer back, and you print it to the page. You could even do multiple problems asynchronously and pass back the answers out of order as they finish. Pretty neat!
The browser kicks of a thread with the javascript you want to execute. So its a real thread, with this web workers thing, your js is no longer single-threaded.
The answer that claimed that "JavaScript is a language, it doesn't define a threading model, it's not necessarily single-threaded" is directly copy-pasted from a medium article... and it confuses without solving the doubt.
It's not necessarily single-threaded, like all other languages. YES... BUT
Javascript is a LANGUAGE meant for Single-threaded programming, and that is the beauty of it and makes it simple and easy to implement.
It is designed around a single Call stack.
Maybe in the future, with new implementations, it will become a Language for multi-threaded programming... but for now, Mehhhhhh.
The Node V8 is still single-threaded, yet it achieves multi-threaded capabilities by creating worker threads on LIBUV which is written in C++.
Same way, even though Javascript is not meant for Multithreading you can achieve limited multithreading by using Browser APIs.
Every time you open a TAB on a browser, it creates a new thread, and the process is the same with web workers.
It works internally BUT does not have access to any window objects.
Yes, People may call it Multithreaded if it makes em Happy,
But in 2021 the Answer is
"JS is meant for Single-threaded programming,(or a single-threaded language) but limited multi-threading can be achieved by using Browser APIs such as Web Workers"
Actually the main confusion, I think here, comes that people are finding clever ways to do things concurrently. If you think about it JavaScript is clearly not multithreaded and yet we have ways to do things in parallel, so what is going on?
Asking the right question is what will bring the answer here. Who is responsible for the threads? There is one answer above, saying that JS is just a language, not a threading model. Completely true!JavaScript has nothing to do with it. The responsibility falls on V8. Check this link for more information -> https://v8.dev/
So V8 is allowing a single thread per JS Context, which means, no matter how hard you try, spawning a new thread is simply impossible. Yet people spawn so-called workers and we get confused. For this to be answered, I ask you the following. Is it possible to maybe start 2 V8 and both of them to interpret some JS code? Precisely the solution to our problem. Workers communicate with messages because their context is different. They are other things that don't know anything about our context, therefore they need some information that comes in the form of a message.
As we are all aware, JavaScript is single-threaded: all code is queued and executed in a sequence.
Using Web Workers, we can run JavaScript processes concurrently (or at least, as close to concurrently as this language allows). The primary benefit of this approach is to handle the manipulation of data in background threads without interfering with the user-interface.
Using web worker:
Web Workers allow you to run JavaScript in parallel on a web page, without blocking the user interface.
Web workers executes in separate thread
Need to host all the worker code in separate file
They aren’t automatically garbage collected, So you need to control them.
To run worker use worker.postMessage(“”);
To stop worker there are two methods terminate() from caller code
and close() from Worker itself
Instantiating a worker will cost some memory.
Web Workers run in an isolated thread. As a result, the code that they execute needs to be contained in a separate file. But before we do that, the first thing to do is create a new Worker object in your main page. The constructor takes the name of the worker script:
var worker = new Worker('task.js');
If the specified file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. The worker will not begin until the file has completely downloaded and executed. If the path to your worker returns an 404, the worker will fail silently.
After creating the worker, start it by calling the postMessage() method:
worker.postMessage(); // Start the worker.
Communicating with a Worker via Message Passing
Communication between a work and its parent page is done using an event model and the postMessage() method. Depending on your browser/version, postMessage() can accept either a string or JSON object as its single argument. The latest versions of the modern browsers support passing a JSON object.
Below is a example of using a string to pass 'Hello World' to a worker in doWork.js. The worker simply returns the message that is passed to it.
Main script:
var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
doWork.js (the worker):
self.addEventListener('message', function(e) {
self.postMessage(e.data); // Send data back to main script
}, false);
When postMessage() is called from the main page, our worker handles that message by defining an onmessage handler for the message event. The message payload (in this case 'Hello World') is accessible in Event.data. This example demonstrates that postMessage() is also your means for passing data back to the main thread. Convenient!
References:
http://www.tothenew.com/blog/multi-threading-in-javascript-using-web-workers/ 
https://www.html5rocks.com/en/tutorials/workers/basics/
https://dzone.com/articles/easily-parallelize-jobs-using-0

JavaScript and single-threadedness

I always hear that JavaScript is single-threaded; that when JavaScript is executed, it's all run in the same global mosh pit, all in a single thread.
While that may be true, that single execution thread may spawn new threads, asynchronousy reqeiving data back to the main thread, correct? For example, when an XMLHttpRequest is sent, doesn't the browser create a new thread that performs the HTTP transaction, then invoke callbacks back in the main thread when the XMLHttpRequest returns?
What about timers--setTimeout and setInterval? How do those work?
Is this single-threadedness the result of the language? What has stopped JavaScript from having multi-threaded execution before the new Web Workers draft?
XMLHttpRequest, notably, does not block the current thread. However, its specifics within the runtime are not outlined in any specification. It may run in a separate thread or within the current thread, making use of non-blocking I/O.
setTimeout and setInterval set timers that, when run down to zero, add an item for execution, either a line of code of a function/callback, to the execution stack, starting the JavaScript engine if code execution has stopped. In other words, they tell the JavaScript engine to do something after it has finished doing whatever it's doing currently. To see this in action, set multiple setTimeout(s) within one method and call it.
Your JavaScript itself is single-threaded. It may, however, interact with other threads in the browser (which is frequently written with something like C and C++). This is how asynchronous XHR's work. The browser may create a new thread (or it may re-use an existing one with an event loop.)
Timers and intervals will try to make your JavaScript run later, but if you have a while(1){ ; } running don't expect a timer or interval to interrupt it.
(edit: left something out.)
The single-threadedness is largely a result of the ECMA specification. There's really no language constructs for dealing with multiple threads. It wouldn't be impossible to write a JavaScript interpreter with multiple threads and the tools to interact with them, but no one really does that. Certainly no one will do it in a web browser; it would mess everything up. (If you're doing something server-side like Node.js, you'll see that they have eschewed multithreading in the JavaScript proper in favor of a snazzy event loop, and optional multi-processing.)
See this post for a description of how the javascript event queue works, including how it's related to ajax calls.
The browser certainly uses at least one native OS thread/process to handle the actual interface to the OS to retrieve system events (mouse, keyboard, timers, network events, etc...). Whether there is more than one native OS-level thread is dependent upon the browser implementation and isn't really relevant to Javascript behavior. All events from the outside world go through the javascript event queue and no event is processed until a previous javascript thread of execution is completed and the next event is then pulled from the queue given to the javascript engine.
Browser may have other threads to do the job but your Javascript code will still be executed in one thread. Here is how it would work in practice.
In case of time out, browser will create a separate thread to wait for time out to expire or use some other mechanism to implement actual timing logic. Then timeout expires, the message will be placed on main event queue that tells the runtime to execute your handler. and that will happen as soon as message is picked up by main thread.
AJAX request would work similarly. Some browser internal thread may actually connect to server and wait for the response and once response is available place appropriate message on main event queue so main thread executes the handler.
In all cases your code will get executed by main thread. This is not different from most other UI system except that browser hides that logic from you. On other platforms you may need to deal with separate threads and ensure execution of handlers on UI thread.
Putting it more simply than talking in terms of threads, in general (for the browsers I'm aware of) there will only be one block of JavaScript executing at any given time.
When you make an asynchronous Ajax request or call setTimeout or setInterval the browser may manage them in another thread, but the actual JS code in the callbacks will not execute until some point after the currently executing block of code finishes. It just gets queued up.
A simple test to demonstrate this is if you put a piece of relatively long running code after a setTimeout but in the same block:
setTimeout("alert('Timeout!');", 5);
alert("After setTimeout; before loop");
for (var i=0, x=0; i < 2000000; i++) { x += i };
alert("After loop");
If you run the above you'll see the "After setTimeout" alert, then there'll be a pause while the loop runs, then you'll see "After loop", and only after that will you see "Timeout!" - even though clearly much longer than 5ms has passed (especially if you take a while to close the first alert).
An often-quoted reason for the single-thread is that it simplifies the browser's job of rendering the page, because you don't get the situation of lots of different threads of JavaScript all trying to update the DOM at the same time.
Javascript is a language designed to be embedded. It can and has been used in programs that execute javascript concurrently on different operating threads. There isn't much demand for an embedded language to explicitly control the creation of new threads of execution, but it could certainly be done by providing a host object with the required capabilities. The WHATWG actually includes a justification for their decision not to push a standard concurrent execution capability for browsers.

Categories

Resources