Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Asynchronous programming requires "consciousness"

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Although we live in an asynchronous world, asynchronous is still unfamiliar to most programming beginners. Learning a programming language usually starts with synchronizing processes, that is, sequence, branching, and looping. And what is the asynchronous process-- start an asynchronous call, and then... There's no such thing as then. Where's the asynchronous program?

Asynchronous programs will run in some asynchronous form, such as multithreading, asynchronous IO, etc., until the processing is complete. What if you need to deal with the results? Give a program entry, let it finish processing the current process, send the results to this entry, and then execute another program, commonly known as a callback. Callbacks generally use the name callback, but sometimes I prefer to use next because it represents the next processing step.

The concept of synchronization and asynchronism

Now we are exposed to some concepts, such as synchronous and asynchronous, what are they?

These two concepts come not from programming languages, but from lower-level instructions, or even lower-level circuits. They are based on two concepts of timing, where "step" refers to pace, so synchronization represents the same pace, while asynchronism represents different steps. Of course, when these two concepts are promoted to the program level, the exact meaning has nothing to do with the clock, but the meaning remains the same.

Synchronization

Give an example of life to illustrate this problem-rule out buying tickets. The ticket office opened a window and a group of people were queuing up to buy tickets in turn. In this line, if the person in front takes a step forward, the person behind can take a step forward; if the person in front is waiting, the person behind must be waiting. Then ideally, everyone can move forward at the same time. OK, everyone at the same pace, is called synchronization.

Here, the ticket window is regarded as a processor, everyone is regarded as an instruction waiting to be executed, and the action of buying a ticket is executing the instruction. It is characterized by a step-by-step shift, if a person buys a ticket for too long (instruction execution time is too long), it will cause blockage.

Asynchronous (multithreaded)

Now more and more people are buying tickets, so the ticket office has opened several more windows to sell tickets at the same time. Each individual team is still synchronized, but the pace between different teams is no longer the same, which is called asynchronism. Queue A ticket sales are smooth, the line is moving forward in an orderly and rapid manner, but a customer in queue B seems to have some trouble in paying, which takes a long time and causes congestion, but this has no effect on queue A.

At this time, the ticket office can be seen as running asynchronous programs in a multi-threaded way. Two characteristics of asynchronism can be seen from this example: first, two asynchronous processes are independent of each other, and they do not block each other (on the premise that there is no need to wait for shared resources); second, the asynchronous program is still synchronous.

Asynchronous (IO)

The above example is more in line with the case of multi-thread asynchronism. What about IO async?

At the end of the year, M is preparing the information for the year-end report, which is an intense work (CPU). We have to collect a lot of data to write some copywriting. For one of the copywriters, M needs production data from the workshop, but a trip to the workshop (IO) can take a long time, so he sends N to the workshop to collect the data, while he continues to write other plans while waiting for N to collect the data (start the asynchronous program). Half a day later, N brings back the data (inserts the event message), M continues to complete the copy on hand (completes the current event loop), and then uses the data brought back by N to start writing the report on the workshop (the new event cycle).

IO is much slower than CPU, so IO asynchronously keeps CPU from sitting idle waiting for the IO operation to complete. When the IO operation is complete, CPU will continue to work with the results of the IO operation as appropriate.

Synchronous logic and asynchronous logic

Coming back to the program, we describe synchronous and asynchronous processing in terms of a function.

Synchronization logic

So, the synchronization process is:

Accept input ⇒ to process ⇒ to produce output

To describe it with a piece of pseudo code is

Note: the pseudocode in this article is close to the JavaScript syntax, and sometimes the type declaration syntax of TypeScript is used to illustrate the type.

Function func (input) {do something with input return output}

This is the standard IPO (Input-Process-Output) processing.

Asynchronous logic

And asynchronism is:

Accept input ⇒ to process ⇒ to start the next step (if any)

To describe it in pseudo code is:

Function asyncFunc (input, next) {do something with input if (next is an entry) {next (output)}}

This process is called IPN (Input-Process-Next).

Notice the Next here. Next, there's only one step. This step includes a number of subsequent steps. So this step can only be followed by several steps to encapsulate a module entry, or function.

Therefore, modularization is a key thought in asynchronous thinking. Many beginners like to write code like a running ledger, which is often hundreds of lines of functions, which is a lack of modular thinking. The idea of modularization needs training, analyzing the correlation of the code, refining functions, extracting objects, and mastering the granularity balance of module refinement after having some experience. This doesn't happen overnight, but I recommend reading books related to Design patterns and Refactoring.

Asynchronous development tools (SDK and syntax level) commitment (Promise)

Consider the above example of the year-end report. When M asks N to go to the workshop to collect data, N will say, "OK, I'll bring the data back soon." this is a promise. Based on this commitment, M can arrange to write the report material about the workshop later. This process is described in pseudo code, which is

Function collectData (): Promise {/ / N to collect data, resulting in a promise return new Promise (resolve = > {collect data from workshop / / this promise will eventually bring data resolve (data)})} function writeWorkshopReport (data) {write report with data} / / A promise to collect data can be used to write a report collectData (). Then (data = > writeWorkshopReport (data))

Some languages, such as JavaScript, use Promise in SDK. However, Task and Task are used in C #, and accordingly, Task.ContinueWith and Task.ContinueWith are used instead of Promise.then.

Asynchronous logic synchronization

The above mentioned the difference between synchronous thinking and asynchronous thinking in one processing step. If you jump out of a processing step, from a larger processing flow, there is not much difference between asynchronous and synchronous, both input-> processing-- > generating output-- > using the output for the next step. The only thing to note is that you need to wait for the output generated by asynchronous processing, which we can call asynchronous waiting. Since we can do something else while doing an asynchronous wait (async wait, await), this wait does not cause blocking. However, because the wait is declared, the compiler / interpreter automatically places the rest of the code after waiting for it to complete, which makes asynchronous code write as if it were synchronous code.

The above example uses pseudo-code that waits asynchronously like this

Async function collectData (): Promise {collect data from workshop / / most languages encapsulate the return value of the async function as Promise return data} function writeWorkshopReport (data) {write report with data} / / await can only be used in the function declared as async async function main () {data = await collectData () writeWorkshopReport (data)} / defines the asynchronous main function, be sure to remember to call it, otherwise it will not be executed main ()

Languages such as C # and JavaScript stipulate that await must be used in functions declared as async at the syntax level, which limits the use of await at the compilation / interpretation level. As long as await is used, it must be in an asynchronous context. Async also requires the compiler / interpreter to automatically handle its return value, for example, in JavaScript, if the return value is not a Promise object, it will be automatically encapsulated into a Promise object; in C #, it will be automatically encapsulated as Task or Task (so the type of the async method needs to be declared as Task or Task).

Attention, attention.

Although language services have done a lot of work on asynchronous program synchronization, they still can't avoid some man-made errors, such as forgetting to write the await keyword. In strongly typed languages, the compiler checks harder, but in JavaScript, forgetting to write await means that a statement that should have taken a value will get a Promise. The interpreter will not question this, but the result of the program running will be incorrect.

Summary

In general, asynchronous programming is not particularly difficult. Using the async/await language feature, you can even write asynchronous code in a way similar to writing synchronous code. But grammatical sugar is sugar after all. If you want to master asynchronous programming better, you still need to understand and be familiar with the concepts of async, callback, Promise, modularization, design pattern, refactoring and so on.

Related reading from small topics gradually to JavaScript asynchronous invocation chat asynchronous invocation "flattening" understanding of JavaScript's async/awaitC# parallel computing (Parallel and ParallelQuery)

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report