57

lets talk about JavaScript code which has setInterval methods every 2 sec.

I also have a onblur animation event for some control.

In a case where onblur occurs (+ animation), I might get the setInterval function.

Question:
Does async programming mean multi-threading? (in any way?)

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 3
    No, asynchronicity (ism?) does *not* require parallelism. – user703016 Jan 22 '12 at 17:55
  • 1
    under the covers there are threads, but as a programmer/language consumer it's not. – Jason Jan 22 '12 at 17:55
  • 2
    @Jason there are no threads under the cover. Or at least there don't have to be. – Raynos Jan 22 '12 at 17:58
  • @Jason: there doesn't have to be more than one thread under the covers either. – jalf Jan 22 '12 at 17:58
  • 2
    not that i don't believe you, but, cite please. i assumed the various javascript runtimes used multithreading to produce asynchronous behavior. – Jason Jan 22 '12 at 18:00
  • am i reading this wrong - it looks like the mozilla js engine employs multiple threads, i can only assume the others do as well: https://developer.mozilla.org/en/SpiderMonkey/JSAPI_Reference/JSRuntime "Only one thread may use a JSContext at a time. In a JS_THREADSAFE build, multiple threads may run JavaScript code concurrently in the same JSRuntime, but each such thread must have its own JSContext." – Jason Jan 22 '12 at 18:06
  • You are reading that wrong. Note the two important caveats: first, you must be building is a JS_THREADSAFE environment, and even then, only one thread per JsContext object. So each individual instance of a javascript context is still singles-threaded. That looks more like one thread per tab/iframe handling, per *context*. Meanwhile, the V8 engine (the javascript behind Chrome) is completely single-threaded, and Node.JS makes a huge deal about that: http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/ – Elf Sternberg Jan 22 '12 at 19:01
  • 1
    Was the .NET tag added accidentally? It seems like the .NET tag isn't relevant to this question (I don't see any .NET Framework content in the post),. – jrh Dec 04 '18 at 13:28

5 Answers5

122

No. It means literally what it means-- asynchronous. Understanding the difference between asynchronous programming and thread-based programming is critical to your success as a programmer.

In a traditional, non-threaded environment, when a function must wait on an external event (such as a network event, a keyboard or mouse event, or even a clock event), the program must wait until that event happens.

In a multi-threaded environment, many individual threads of programming are running at the same time. (Depending upon the number of CPUs and the support of the operating system, this may be literally true, or it may be an illusion created by sophisticated scheduling algorithms). For this reason, multi-threaded environments are difficult and involve issues of threads locking each other's memory to prevent them from overrunning one another.

In an asychronous environment, a single process thread runs all the time, but it may, for event-driven reasons (and that is the key), switch from one function to another. When an event happens, and when the currently running process hits a point at which it must wait for another event, the javascript core then scans its list of events and delivers the next one, in a (formally) indeterminate (but probably deterministic) order, to the event manager.

For this reason, event-driven, asynchronous programming avoids many of the pitfalls of traditional, multi-threaded programming, such as memory contention issues. There may still be race conditions, as the order in which events are handled is not up to you, but they're rare and easier to manage. On the other hand, because the event handler does not deliver events until the currently running function hits an idle spot, some functions can starve the rest of the programming. This happens in Node.js, for example, when people foolishly do lots of heavy math in the server-- that's best shoved into a little server that node then "waits" to deliver the answer. Node.js is a great little switchboard for events, but anything that takes longer than 100 milliseconds should be handled in a client/server way.

In the browser environment, DOM events are treated as automatic event points (they have to be, modifying the DOM delivers a lot of events), but even there badly-written Javascript can starve the core, which is why both Firefox and Chrome have these "This script is has stopped responding" interrupt handlers.

Elf Sternberg
  • 16,129
  • 6
  • 60
  • 68
  • 1
    What about ajax calls in jQuery , the server side code do its stuff while my browser keeps do other functions.....? – Royi Namir Jan 22 '12 at 20:00
  • 20
    Those aren't threads, though. You've sent a message in your browser-side code to the server. *When the call returns* is an event, and your code is expected to pick it up and do something with it. While it's waiting, the eventloop goes to handle other events. When your event returns, the eventloop gives your callback complete control over the single process thread until you give it up by reaching the end of the callback, doing something that causes the eventloop to progress, or creating a new event. – Elf Sternberg Jan 22 '12 at 22:46
  • 16
    a great answer, thanks for explaining that in a reasonably jargon-free manner – Jason Jan 23 '12 at 07:37
  • Why "anything that takes longer than 100 milliseconds should be handled in a client/server way"? Ajax calls take more than 100 ms sometimes, and my browser doesn't give me the "This script is has stopped responding" message. – trusktr Feb 11 '14 at 21:01
  • 2
    Trusktr: Because node is single-threaded, you shouldn't use the process you're using to handle requests, to also do heavy programmatic lifting; you shouldn't use the same process to do natural language processing, or image processing; you should do that in child processes. Each process will take time; every other process will be blocked until its done. If you do it in child processes, you free your "switchboard" process to handle I/O. – Elf Sternberg Feb 11 '14 at 23:45
  • 2
    Ajax calls *are* client/server. – Arel Oct 22 '17 at 17:13
  • The event loop is a second thread though behind the scenes - the little man listening for the events. Or am I missing something here? – Eliezer Steinbock Apr 04 '18 at 23:48
  • The concept behind is the same. But today the word "thread" is firmly attached to one specific meaning, so people will misunderstand you when you say "hey but there are many things in progress and they can work almost independently and remember their own stuff". Yes. You could call it multitasking, multiprocessing, multithreading, but each of those are allocated for a specific thing and TECHNICALLY it's not the same. But yes you've found a good connection between two areas and their underlying concept is the same. It is "a kind of" multi-threading. – dkellner Feb 17 '20 at 23:10
  • @EliezerSteinbock 'async event handling' is the inbound side, and 'multi-threading' is one way of handling the outbound side. So I suggest using the term 'async event handling' instead of 'multi-threading' for the 'event loop'. With particular notice that it is the execution environment (client/server, user/computer, or process/process like disk I/O) that makes it async, not necessarily multiple threads used by a single process on your computer (even though that could be one such execution environment). – Magne May 24 '20 at 16:16
  • The jargon-free-ness of this answer is mesmerizing. – Hiro Apr 29 '21 at 17:57
  • Just to pick up one one thing as someone who comes from the background of systems programming languages. Synchronization between threads is *not* done by locking *memory*. What you refer to here is mutexes which wrap atomic operations, those operations lock *thread execution*. However it often looks like regions of memory are being locked because you can have multiple mutexes and they are *usually* associated with a particular use/purpose which conceptually stores data in a region of memory. Read more here: https://stackoverflow.com/a/70474689/893254 – FreelanceConsultant Dec 27 '22 at 20:30
  • By the way, what I take away from this answer is fundamentally this: Your JS code is *probably* executing in a single thread and `await` tells the code interpreter to suspend execution on the currently `await`ing line and go and fetch some tasks from an event queue instead. – FreelanceConsultant Dec 27 '22 at 20:34
  • > This happens in Node.js, for example, when people foolishly do lots of heavy math in the server-- that's best shoved into a little server that node then "waits" to deliver the answer. Node.js is a great little switchboard for events, but anything that takes longer than 100 milliseconds should be handled in a client/server way. < If I understand correctly, this frees up the main server to take more requests, while the little server does the heavy processing. BUT, the total processing time remains the same? – Apoorve Feb 19 '23 at 21:24
8

A single threaded event loop is a good example of being asynchronous in a single threaded language.

The concept here is that you attach doLater callback handlers to the eventLoop. Then the eventLoop is just a while(true) that checks whether the specific timestamp for each doLater handler is met, and if so it calls the handler.

For those interested, here is a naive (and horribly inefficient toy) implementation of a single threaded event loop in JavaScript

This does mean that without any kind of OS thread scheduler access of your single thread, your forced to busy wait on the doLater callbacks.

If you have a sleep call you could just do sleep until the next doLater handler which is more efficient then a busy wait since you deschedule your single thread and let the OS do other things.

Raynos
  • 166,823
  • 56
  • 351
  • 396
2
  1. No asynchronous programming doesn't mean multithreading specifically.

  2. For achieving multiple tasks at the same time we use multi-threading and other is event loop architecture in node js.

  3. JavaScript is synchronous and single threaded and that is why node js is also single threaded but with event loop node do a non-blocking I/O operations. Node.js uses the libuv library that uses a fixed-sized thread pool that handles the execution of parallel tasks.

Thread is a sequence of code instructions and also the sub unit of process.

In multi-threading, processes have multiple threads. In single threading, processes have single thread.

Bilal Yaqoob
  • 790
  • 1
  • 10
  • 22
1

Only in the sense that it executes code haphazardly and risks race conditions. You will not get any performance benefits from using timeouts and intervals.

However, HTML5's WebWorkers do allow for real multithreading in the browser: http://www.html5rocks.com/en/tutorials/workers/basics/

Jeffrey Sweeney
  • 5,986
  • 5
  • 24
  • 32
-5

If there is a callback, something has to call it. The units of execution are threads & so, yes, some other thread has to call the callback, either directly or by queueing up some asynchronous procedure call to the initiating thread.

Martin James
  • 24,453
  • 3
  • 36
  • 60
  • 2
    It's perfectly possible for the _same single thread_ to call the callback later. – Raynos Jan 22 '12 at 18:07
  • @Raynos how? If one thread directly calls a function, it's just called a 'call'. If the callback is signaled into the thread on some input loop, something must have queued the callback. A driver could do this directly, but it's usually a kernel thread. – Martin James Jan 22 '12 at 18:26
  • 2
    By having the entire event loop live in the single thread. Note that the thread can't do any IO then, it can only do asynchronous communication with itself and anything within the single thread. This might be pedantry. – Raynos Jan 22 '12 at 18:30
  • 2
    It's not pedantry, Raynos. You're right. It's a single thread of execution, the program pointer is a singleton. Learning to visualize the event queue and the functions hanging off of it-- and learning to respect that, in event-driven programming the function does *not* return to where it left off-- was the single biggest key to my understanding node.js. – Elf Sternberg Jan 22 '12 at 18:55
  • I think we're all arguing the same point from different ends. From the OS side, there has to be something loading the events onto the queue. In that respect, 'Does Async programming means - multi Threading ? ( in some way ) ?' the answer has to be yes. From the js side, things look different. – Martin James Jan 22 '12 at 19:00
  • 2
    No, the answer doesn't have to be multi-threaded. Do not confuse OS scheduling, programmer-level threading, and asynchronous event handling. That Way Lies Madness. – Elf Sternberg Jan 22 '12 at 19:05
  • Relevant to this discussion: [The Mozilla Javascript Runtime is now officially single-threaded](http://blog.mozilla.com/luke/2012/01/24/jsruntime-is-now-officially-single-threaded/) – Elf Sternberg Jan 25 '12 at 19:23
  • He's correct in that his point is some other thread *may be* responsible for populating the events in the event loop. But it doesn't always have to be. When it comes to things like networking events, data received from a socket, then of course, another thread is responsible for populating the event queue - even if that is the OS thread, at some level. How the answer has been written is confusing however, and it isn't the case that `await` causes another thread to be spawned. – FreelanceConsultant Dec 27 '22 at 20:37