ChatGPT解决这个技术问题 Extra ChatGPT

Asynchronous vs Multithreading - Is there a difference?

Does an asynchronous call always create a new thread? What is the difference between the two?

Does an asynchronous call always create or use a new thread?

Wikipedia says:

In computer programming, asynchronous events are those occurring independently of the main program flow. Asynchronous actions are actions executed in a non-blocking scheme, allowing the main program flow to continue processing.

I know async calls can be done on single threads? How is this possible?

JavaScript doesn't have threads, but it does have asynchronous method calls.
Any system where one process manages multiple sub-processes, the control process can provide asynchronous operation of the sub processes. In the case of JavaScript, the browser provides the compute stream. When some function makes an async call, the browser can store the context for that function. Now that same single browser thread can change context to resume execution of another function. Whereas in traditional multi-threaded programs, one thread performing one function blocks to allow another thread to run a different function. Each thread performs its own function synchronously.

k
karunski

Whenever the operation that needs to happen asynchronously does not require the CPU to do work, that operation can be done without spawning another thread. For example, if the async operation is I/O, the CPU does not have to wait for the I/O to complete. It just needs to start the operation, and can then move on to other work while the I/O hardware (disk controller, network interface, etc.) does the I/O work. The hardware lets the CPU know when it's finished by interrupting the CPU, and the OS then delivers the event to your application.

Frequently higher-level abstractions and APIs don't expose the underlying asynchronous API's available from the OS and the underlying hardware. In those cases it's usually easier to create threads to do asynchronous operations, even if the spawned thread is just waiting on an I/O operation.

If the asynchronous operation requires the CPU to do work, then generally that operation has to happen in another thread in order for it to be truly asynchronous. Even then, it will really only be asynchronous if there is more than one execution unit.


Well explained, Thank you; but I have a question here. You mentioned that "For example, if the async operation is I/O, the CPU does not have to wait for the I/O to complete. It just needs to start the operation". My question is when the program is single threaded, and say in code line 3, you call a I/O operation, then how can you start the operation in line 3 and execute the line 4 without waiting for the I/O operation to complete? For me, I have to put the code in line 3 in a new thread to achieve the line 4 to execute without waiting for completion of the I/O operation.[Java pgm perspective]
the reason being, Though the CPU does not have to wait, CPU will wait for the I/O operation to complete ... I believe your second paragraph is the answer for my query. In such a case, I need to conclude that in Java, asynchronous calls need to be executed in a different thread. Please correct me if i am wrong or let me know if i have to post a new SO qn
@spiderman Some languages, like Node.js, have an async programming model. The language and runtime provide built-ins that allow line 4 to be executed in the same thread, even before the IO operation completes. This is achieved by line 3 providing a callback that the runtime will invoke when the IO finishes.
@spiderman maybe...the OS's Async function just return false or something directly.
M
Michael Kohne

This question is darn near too general to answer.

In the general case, an asynchronous call does not necessarily create a new thread. That's one way to implement it, with a pre-existing thread pool or external process being other ways. It depends heavily on language, object model (if any), and run time environment.

Asynchronous just means the calling thread doesn't sit and wait for the response, nor does the asynchronous activity happen in the calling thread.

Beyond that, you're going to need to get more specific.


So basically am I right in saying: Multi-threading == Using multiple threads in order to provide processing benefits on processor intensive tasks that are [ideally] able to benefit from the multiple processors, as well as benefits in asynchronous situations. Asynchrony == a process that does it's thing, while the state that called the process does not have to wait for it to complete. (Might not necessarily use multiple threads to do this-- ie. other hardware components may take responsibility).
@Michael - Could you please explain how asynchronous programming could happen in a single thread with an example?
@KumarVaibhav - the most common example is when a single thread works on items from a queue (for instance, the Windows message queue). If the program is in the habit of sending items into it's own queue (a common pattern) then the bit of code that sends the item doesn't wait for the operation to finish, but rather just returns. The operation will be taken care of in due course by the main loop.
There can be a difference between how code is written and how it is executed. For example, in C#, I can have a method that starts an async task, my method is fully async aware and can do other things without waiting for the task to complete. However, the CLR can also decide to inline my task and execute it synchronously.
which thread execute the awaited task? the method marked with a-sync is executed synchronously till it reach the await keyword, at this point which thread execute this await-able task?
J
Jason Orendorff

No, asynchronous calls do not always involve threads.

They typically do start some sort of operation which continues in parallel with the caller. But that operation might be handled by another process, by the OS, by other hardware (like a disk controller), by some other computer on the network, or by a human being. Threads aren't the only way to get things done in parallel.


G
George V. Reilly

JavaScript is single-threaded and asynchronous. When you use XmlHttpRequest, for example, you provide it with a callback function that will be executed asynchronously when the response returns.

John Resig has a good explanation of the related issue of how timers work in JavaScript.


M
Murugan Gopalan

Multi threading refers to more than one operation happening in the same process. While async programming spreads across processes. For example if my operations calls a web service, The thread need not wait till the web service returns. Here we use async programming which allows the thread not wait for a process in another machine to complete. And when it starts getting response from the webservice it can interrupt the main thread to say that web service has completed processing the request. Now the main thread can process the result.


I would disagree a little bit. I wrote a single threaded HTTP server that handled multiple simultaneous requests using async IO completion. Async doesn't require things to happen in multiple paths of execution, it just means multiple compute streams can overlap. Another way to look at it is that on a single threaded OS, I can have 2 processes running "simultaneously". From each process' point of view, they are running synchronously. However, from the OS point of view, it is operating async.
I had to scroll too far before finding an answer which recognised that threading and sync are two separate concepts.
O
Otávio Décio

Windows always had asynchronous processing since the non preemptive times (versions 2.13, 3.0, 3.1, etc) using the message loop, way before supporting real threads. So to answer your question, no, it is not necessary to create a thread to perform asynchronous processing.


@dmckee - it is interesting how different systems evolve in similar manners.
M
Mike

Asynchronous calls don't even need to occur on the same system/device as the one invoking the call. So if the question is, does an asynchronous call require a thread in the current process, the answer is no. However, there must be a thread of execution somewhere processing the asynchronous request.

Thread of execution is a vague term. In a cooperative tasking systems such as the early Macintosh and Windows OS'es, the thread of execution could simply be the same process that made the request running another stack, instruction pointer, etc... However, when people generally talk about asynchronous calls, they typically mean calls that are handled by another thread if it is intra-process (i.e. within the same process) or by another process if it is inter-process.

Note that inter-process (or interprocess) communication (IPC) is commonly generalized to include intra-process communication, since the techniques for locking, and synchronizing data are usually the same regardless of what process the separate threads of execution run in.


d
dmckee --- ex-moderator kitten

Some systems allow you to take advantage of the concurrency in the kernel for some facilities using callbacks. For a rather obscure instance, asynchronous IO callbacks were used to implement non-blocking internet severs back in the no-preemptive multitasking days of Mac System 6-8.

This way you have concurrent execution streams "in" you program without threads as such.


M
Milan Babuškov

Asynchronous just means that you don't block your program waiting for something (function call, device, etc.) to finish. It can be implemented in a separate thread, but it is also common to use a dedicated thread for synchronous tasks and communicate via some kind of event system and thus achieve asynchronous-like behavior.

There are examples of single-threaded asynchronous programs. Something like:

...do something
...send some async request
while (not done)
    ...do something else
    ...do async check for results

L
LeopardSkinPillBoxHat

The nature of asynchronous calls is such that, if you want the application to continue running while the call is in progress, you will either need to spawn a new thread, or at least utilise another thread you that you have created solely for the purposes of handling asynchronous callbacks.

Sometimes, depending on the situation, you may want to invoke an asynchronous method but make it appear to the user to be be synchronous (i.e. block until the asynchronous method has signalled that it is complete). This can be achieved through Win32 APIs such as WaitForSingleObject.


This is true on some systems, but not all. Unix doesn't require you to spawn or utilise another thread, unless you call the kernel another thread, which I suppose is one way to look at it.
This isn't true on Windows either. Overlapped I/O, for example, is asynchronous.