Related technologies for concurrency, synchronization, asynchronous, and event-driven programming in web development

Source: Internet
Author: User

First, the opening language

my previous article, "How to provide Web server concurrency efficiency of asynchronous programming technology" has become the blog Garden "Editorial Recommendation" article, this is a great encouragement to my blog, perhaps the reason for being recommended many children's shoes in this article commented, there are children's shoes said my article is very theoretical, there is no actual code and specific projects to support, this review let me have a theory and practice out of the taste, so I want to talk about why I write this article reasons, This article is a summary of how I learned multithreaded programming before long.

When I found all the books in my book that were related to multithreaded development, I found a problem, the most powerful practice in developing multithreading in Java is to do the concurrency of the server, and the other applications are pediatrics, and this practice is of great economic value for every web programmer. So I want to take this practice to continue to learn multi-threading, and then I found that concurrent processing this block is inseparable from IO processing, while the merits of IO processing directly related to the efficiency of concurrent processing, about the concurrency of knowledge, some people say it is best to write code, tell us how the API is used, To tell the truth simple to write a few lines is not too difficult things, write a few lines of code does not mean that you can master it, mastering multithreading is not to focus on understanding a few lines of code, to understand after the epiphany come: Oh, understand.

To really master a certain technology you have to know the reason why, but it is not so easy to sort out the reason for concurrency, this is actually a design idea, rather than a few simple lines of code, a few JDK provided by the API, code and API just to practice these ideas of implementation, I learned thread development before, Learning IO API, this process is very early, but this process is basically remember to forget to remember the dead cycle of forgetting again, the reason is because their own design thinking is too esoteric, you do not understand the design idea, you can not connect those APIs in tandem, so the final result will only be forgotten. The essence of technology is the tool, the premise to use a good tool is to really understand the value of the tool, which is like the axe designed to cut wood, the kitchen knife designed for cutting vegetables, if we use an axe to cut vegetables, knives used for chopping wood, this must be fool, for such a complex tool like threading and Io, Use and use like this simple tool kitchen knife and axe, should be the thing to do their own work, the trouble with complex tools is more difficult to understand, I have to spend a little more time and effort.

I write a lot of code in my early articles, but I write more in recent articles, and I want to have a better understanding of the technology I know, so there are more theories and speculations.

The title of this article is "about concurrency, synchronization, asynchronous and event-driven programming in web development," the purpose of this article is to work with you to understand the very common concepts in the title, by understanding them, to guide our future study and use of these concepts.

Second, let's take a good understanding of the three concepts of concurrency, synchronization, and Asynchrony

The title of the three concepts in the field of web development is too common, even if the introduction of web development of children's shoes to find the web development of the book can be found in this three concepts, but if you do not understand the three concepts thoroughly, if in the actual development of the three concepts of the intertwined problem, it is estimated that many people will be numb head.

Concurrent

The first is the concept of concurrency, and let's look at examples of concurrency in reality.

A first example:

One day you cook at home, you have a very good mood this day, want to eat a meal, so to have a dish has soup and wine to drink, began to dry, you will first in the rice cooker to cook, rice in the cooking, you will take time to buy a bottle of beer, bought a beer back home you will cook, you want to make a soup, in order to save time, You will first boil boiling water, boil boiling water at the same time, you will cut vegetables, cut good vegetables will have to stir-fry, the process of the following omitted 10,000 words, the earth people I want to understand the future is how, I will no longer tell the details.

The above description of cooking, boiling water, buy beer, cut vegetables, stir fry, they can be used as a separate task, these tasks are to achieve a specific purpose, they are not interchangeable with each other, but in practice you do not wait for a task to do another task, but will use a coordinated approach, Cross, the advantage of doing so is high efficiency, save time, this and programmers usually work similar, while writing programs, while listening to songs, while chatting with friends and colleagues in QQ.

A second example:

  In real life there is a kind of concurrency, for example, we eat in the cafeteria, to the cafeteria to eat a lot of people, so the canteen opened a few dozen rice window, if the window open more, then eat people hit the meal time is the least, if each diner has a window one-to-one service, So diners basically do not have to waste any time to wait, this VIP feeling in China so resource-intensive country, is simply too cool, the canteen to eat the concurrency and I mentioned in the last article of the Web server concurrency similar.

Here are a list of two concurrent instances, it seems a bit superfluous suspicion, but if we carefully study the two examples, they actually have a fundamental difference, the first example is actually a person's concurrency, the second example is the concurrency of many people, the concept of a computer is described as the previous example is a thread to complete the concurrency, The latter example is the multi-threaded completion of the concurrency, the first example of the thread carrier is the person who cooks, the second thread of the carrier is every meal window staff, these two examples can actually analogy to my last article referred to the practice of the two and practice three, especially the first example, although this scene people are very familiar with, But in the program development there are many people put the first instance and sent to forget, especially for web development, concurrency is multithreading, how a thread can do concurrency, but example of a thread can do concurrency.

By the above description, I'm going to give my own summary of the concurrency definitions:

Concurrency is to allow a series of independent tasks to execute simultaneously, while the execution consists of two situations, one is completely independent execution, for example, in a computer with a dual-core processor, each CPU at the same time to deal with different tasks, the other is a task is not finished, CPU computing is used to handle other tasks when the CPU is idle.

And in reality, we have to be efficient concurrency of the two patterns to be mixed together to use, canteen meal is a mixture of two modes of concurrency, for the computer two mixed concurrency can be the computer's computational ability to dig deep, so the three is mixed two concurrency, the practice is three-efficient and advanced, The third approach is worth popularizing.

Next talk about the two concepts of synchronous and asynchronous, remember just work soon, there is a time to participate in the interview, the interviewer asked me what is synchronous what is asynchronous, I was the answer is: Synchronization is single-threaded, asynchronous is multi-threaded, then the interviewer paused, told me that this explanation no problem, But in real-world development, this answer doesn't allow you to use synchronization and asynchrony very well. Now recall that the interviewer gave me the assessment of the answer is still reasonable, I began to talk about synchronous and asynchronous.

  Synchronous:

In the field of computer synchronization should be a separate task one after another run, take the above cooking example description is cooked to go to the supermarket to buy beer, wine bought in order to cut vegetables, vegetables cut to stir-fry, vegetables cooked to boil soup, obviously synchronized in real life efficiency is very low, However, there is a great advantage of synchronization is simple, simple theoretical basis is to do one thing at a time, do the time wholeheartedly absorbed.

  Asynchronous:

The following is the concept of asynchronous, synchronous and asynchronous in the modern computer field is two equivalent concept, but if we want to trace the nature of asynchrony, we will find that synchronous and asynchronous is actually a causal relationship, synchronization is because, asynchronous is the fruit, in other words synchronous is asynchronous this child his mother, So we have to understand the asynchronous to understand the synchronous do not do bad things, in the Web front end there is a vivid example of this problem, this example is Ajax, before the advent of Ajax, the browser of a separate page and server interaction is through a socket, This socket is equivalent to a thread, it is the use of synchronous processing, so there is no Ajax era, a separate page each and server interaction can only do one thing, and the network processing speed is often the slowest, and the efficiency of the network is vulnerable to external influence, So the synchronization request will cause the user to use the page experience is very bad, the synchronization of the site is always testing the user's patience, which leads to the advent of Ajax, Ajax is the essence of the browser provides a new socket link, this socket is different from the synchronous socket, It can be independent of the synchronous socket run, with Ajax this socket we can not affect the page synchronization operation can also get data from the server, this is like the browser by the original one person to complete and the service side of the interaction into the now two people to complete and the service side of the interaction, they do their duties, Together to complete the functionality on the page.

  Asynchronous and concurrency relationships and differences:

asynchronous operations and concurrency look very much like, especially as I talked about the concurrent cooking instances, it is true that concurrency and asynchrony are often intertwined, but they are still very different, the difference is that they achieve the business purpose, concurrency is business meaning can do more things, and asynchronous is to let many people together to complete a task , asynchronous is actually through a professional perspective of a large task into a relatively independent small task, so that more professional people to complete this small task, the small task is completed after the final summary into a large task results, the above Ajax is the truth, in fact, I previously focused on the Hadoop is a typical asynchronous task system.

Asynchronous and concurrency common are through multithreading to achieve, through their differences in business scenarios, we learn multi-threading in turn, we know what multithreading can do for us, then when you encounter the need to use multi-threaded business scenarios to know what to analyze the business scenario.

Third, about event-driven programming

In my last article I repeatedly wrote a lot of events to drive these four words, to the event driver in this article I added two characters programming, why add it I will talk about later.

What kind of programmer is the most familiar event-driven programmer in the world? The answer is front-end engineers, whether it is the desktop front-end or the Web front-end are the most familiar event-driven, to the Web front-end For example, we do not think of what the Page object-oriented programming, what jquery framework for use, but for the button, adding related events for the page element operation is certainly indispensable, and the event-handling mechanism of the Web front-end is the standard event-driven mechanism, in order to clarify the event-driven, here I review the page of the event mechanism, we develop the page event, the first step is to define the event (defining the event is to define a function) or to define an action for the event, and binds the event to the specified element, if we do not trigger the event on the element, then the defined function will not execute, and if the event on the element is triggered, the defined function will execute. The code is not provided, this is too simple and usual.

About the browser event mechanism implementation, I looked for a long time did not find the complete information, so here I ventured to speculate on the implementation of the event mechanism, the following content is entirely my guess, not necessarily with the actual match, the following:

First of all, I would say that there is a classic design method in the multi-line development process, which is the production-consumer model, the production-consumption model is characterized by the producer and consumer are separated by an intermediary queue, whether the production request or consumption results are transferred through this intermediary queue, so that the producer and consumer relations can be decoupled , the event implementation mechanism is similar to the production-consumption model, which is not the design idea, but the middle layer of communication between the two sides.

There should be an event handler in the event handling mechanism, where the event handler is located in the middle of the element and event handling method, where we define the event as the relationship between the element and the event handling method defined in the event handler, and when the corresponding relationship is defined, the event handler initiates a dead loop. This loop repeatedly detects changes in the state of the element, and when the event handler discovers that a state has changed, the processor finds the corresponding event-handling method and executes the method.

Nodejs is an event-driven language, which is the official definition of Nodejs, and many comments say Nodejs is the first programming language to drive event-driven ascent to the language level. So in this article I added the programming two words behind the event driver.

Traditional language development is done in chronological order, this can not only reduce the language learning costs, but also make the development of code ideas easier to control, but the real scene is complex, this sequence of events based on the development process is not necessarily the best way to solve real problems. It's like we do one thing, we get into a lot of things when we do it, and because of what happens, the results of this thing can change depending on the situation, and if you want to do it in chronological order, it makes the program very complicated. Because we're going to make different execution paths in chronological order, that's the way the permutations are arranged, which obviously complicates things, and if we use event-driven programming, we just define the cause of the transaction, the different process situations, and the results we can get, In other words, we first focus on the entity content and ignore the transaction relationship problem, and the transaction relationship is defined in the event handler, when we send an indicator signal to the event handler, the processor will find a corresponding behavior, then event-driven programming simplifies the process of program development.

The core technique of event-driven programming is that the method can be transformed into an object that can be passed in the process of event processing, the method gets the command of the event manager in the appropriate position, which is called the callback function, and the JavaScript language function can be passed as an object. It also ensured that event-driven programming went up to the language level, and I think that's one of the important reasons why Nodejs authors use Google's V8 engine to design Nodejs.

The callback function alters the process of traditional program development, but the large number of code that uses the callback function can often become obscure, which is one of the important reasons for JavaScript language mastery. Given that the problem with the callback function is promise programming, Promise's goal is to make the callback programming look like chronological programming, I studied the next promise in the front-end time, but did not delve into it, because the callback is difficult to understand, the callback becomes sequential programming, it is not more confused , according to the current technical characteristics, I will choose to use promise technology carefully.

Iv. Summary

The main content of this article to this end, in view of the previous article some of the content has a lot of controversy, this article wants to do some explanation: above the biggest problem or IO interpretation, I admit that I actually understand the IO is not too deep, so I just use words to describe the processing of non-blocking IO, this text written when I was very careful, Try not to talk too much, I was only using a concept to write this implementation, that is, the implementation of non-blocking IO will certainly have a similar to the event processor in the middle tier to coordinate the IO operation and CPU operation, I am confident that there is no mistake. In fact, IO technology is quite complex in Java, more difficult to learn, now the JDK provides the IO model has three major categories, BIO (blocking IO), NIO (Blocking IO or new IO) and AIO (asynchronous IO or NIO2.0), the IO of the JDK is built on the OS io, so learning io really takes a bit of thought and effort, which is a key point of my study in the future.

In addition, no matter what tasks in the computer will contain the IO operation and CPU computing two processes, IO speed problem often drag the CPU calculation, because some IO is too slow, if you stand in the CPU angle, it is too expensive to wait for IO processing, So advanced Io is in order to adjust the relationship between IO processing and CPU computing, I think the new IO solution to solve the core problem.

Well, this article is written here, this article is similar to the above is to talk about some of their own understanding of the technology, a lot of text, almost no code, I hope children's shoes to shoot more bricks, there are problems to progress faster.

 

Related technologies for concurrency, synchronization, asynchronous, and event-driven programming in web development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.