原文: https://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/

--------------------------------------------------------------------------------------------------------

How is javascript asynchronous AND single threaded? ?

Asynchronous programming is one of those programming paradigms that’s extremely difficult to fully understand, until you’ve done enough of it in practice. In an ideal world this shouldn’t be the case, so here’s yet another attempt to explain the concept of async programming, and why its different from parallel programming, in the context of javascript.

Everything runs on a different thread except our code.

At first glance, this sentence doesn’t seem to make a lot of sense. Isn’t everything we execute technically “our code”? Well, yes and no. Lets take a look at two examples of synchronous and asynchronous implementations of the same functionality. Synchronous implementation (python) :

import requestsr = requests.get('http://sohamkamani.com') print r.text print "I come after the request"

Async implementation (js) :

var request = require('request'); request('http://sohamkamani.com', function (error, response, body) { console.log(body); }) console.log('I come after the request');

Now, all the above code runs on the same thread, no doubt about it. But what were missing is that the request and requests libraries, make http requests that go to other servers. The time spent in sending the request, processing it server side, and returning the response, is not spent in our thread. Thats what the web server you sent the request to does.
In our python implementation, we wait for all these processes to complete and receive the response before moving on to executing the next line of code. The async philosophy adopted by javascript and Node.js is fundamentally different in this regard. Instead of waiting for the response before executing the next bit of code, we declare what we want to happen once we receive our response, and move on to the next bit of code as usual.
This is why "I come after the request" will always get printed to the console after the response in the case of our python code, and always get printed before the response for our javascript code[1].

What good does any of this do me?

Both the snippets of code are exactly similar in their functionality :

  1. import requests == var request = require('request');
  2. r = requests.get('http://sohamkamani.com') == request('http://sohamkamani.com', ... )
  3. print r.text == console.log(body);
  4. print "I come after the request" == console.log('I come after the request');

Let us assume, for the sake of experimentation, that each of the 4 snippets of code above take ~10ms to execute. Since we are only here to see the power of async, we are not going to take the raw execution speed of either language into consideration, and assuming the synchronous parts of both examples to have the same execution time (of 10ms). We will also take two cases of waiting time into consideration, one of 20ms, and one of 5ms.

Case 1 (Waiting time = 20ms)

With synchronous execution :
Sync 20ms

With asynchronous execution :
Async 20

Snippet 4 doesn’t have to wait for our response to arrive in order to execute, but snippet 3 does. Our javascript code handles this by defining tasks that need to wait inside the callback and other tasks outside of it. In the case of our python example, all code after we send the request is blocked until the response arrives.
This gives us a net loss of 10ms in this case for the synchronous implementation.

Case 2 (Waiting time = 5ms)

With synchronous execution :
Sync 20ms

With asynchronous execution :
Async 20

Synchronous execution with a smaller waiting time doesn’t look much different from the last picture, but the asynchronous timing diagram is pretty interesting. We see that snippet 4 starts execution as usual during waiting time, but snippet 3 doesnt execute right after the waiting time is over. This is because snippet 3 and snippet 4 are running on the same threadand hence snippet 3 has to wait for 4 to finish before it can start. This is a much better illustration of what it means to be single threaded and asynchronous.

Final thoughts

If async is so obviously the correct thing to do, then why should we bother with synchronous programming?

The first thing that stands out in the javascript code snippet is that it’s much less simple than the corresponding python snippet, and so takes a bit more time to read, understand, and develop. In fact, there are many articles and blog posts dedicated to managing async code, because without proper management, it can all get out of hand pretty quickly.

For rapid prototypes, or in cases where speed and timing is not the main concern, going the synchronous way can be more productive. On the other hand, if you’re planning to build an application with a lot of I/O and networking tasks, or with a lot of users, then the power of async really starts to shine.

Although async is not embedded in pythons “philosophy”, like it is with NodeJs, there are many libraries which let you leverage event driven and async programming, like the Twistedlibrary.

How is javascript asynchronous AND single threaded?相关推荐

  1. 多线程编程模式之Single Threaded Execution 模式

    一.Single Threaded Execution 模式介绍 简单的来说,Single threaded execution 模式描述了在一种多线程环境下各个线程对于公用资源的使用方式--任一时刻 ...

  2. java多线程之Single Threaded Execution模式

    一.简介 所谓Single Threaded Execution模式,就是指"以一个线程执行",就像一座独木桥同一时间内只允许一个人通过一样,该模式用于设置限制,以确保同一时间内只 ...

  3. java single threaded_[Java多线程设计模式]读书笔记 - 第一章 Single Threaded Execution

    Single Threaded Execution是指"以1个线程执行"的意思.就像细独木桥只允许一个人通行一样,这个Pattern用来限制同时只让一个线程运行. Single T ...

  4. Single Threaded Execution模式

    以下是学习了<图解Java多线程设计模式>一书中记录的内容 Single Threaded Execution模式--能通过这座桥的只有一个人 Single Threaded Execut ...

  5. Single Threaded Execution Pattern

    如果不使用Single Threaded Exception Pattern: 门类: 人类: main: 执行结果: 为什么会有broken(损坏): Gate是非线程安全的类. 测试并无法证明安全 ...

  6. 一 、Single Threaded Execution 模式

    当我们修改多个线程共享的实例时,实例就会失去安全性.所以,我们应该仔细找出实例状态不稳定的范围,将这个范围设为临界区,并对临界区进行保护,使其只允许一个线程同时执行. JAVA使用synchroniz ...

  7. 第一章Single Threaded Execution模式 能通过这座桥的只有一个人

    [Single Threaded Execution模式] 以一个线程执行,就像独木桥同一时间内只允许一个人通行一样,该模式用于设置限制.以确保同一时间内只能让一个线程执行处理. Single Thr ...

  8. javascript功能_功能性JavaScript简介

    javascript功能 Hey everybody! I've written a book called Discover Functional JavaScript, and it's now ...

  9. node.js使用手册_权威的Node.js手册

    node.js使用手册 Note: you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or ...

最新文章

  1. 【正一专栏】从人民的名义看失败的婚姻关系
  2. php 文字换行,用Php中的Fpdf换行文本
  3. linux eclipse java_从Linux终端编译运行Eclipse Java项目
  4. 使用display inline-block 布局时,出现的间距问题的解决办法和相关说明
  5. win10 uwp 让焦点在点击在页面空白处时回到textbox中
  6. CSS3最颠覆性的动画效果,基本属性[3D]
  7. dj电商-需求分析-商品模块
  8. 启用nf_conntrack模块,避免table full dropping
  9. 4.5 Spark SQL 处理JSON数据
  10. 0018-大数据售前的中年危机
  11. 搭建python本地源
  12. 马士兵Python基础版2020教程P98-P134 PPT笔记+课堂代码
  13. 使用MVPArms框架时,访问网络没响应。
  14. 关于生成树的一些小东西
  15. 3D游戏之父--John Carmack连载系列(四)
  16. Vue学习随笔+商城项目【上】
  17. centOS域名访问问题,/etc/hosts详解
  18. 数据库SQL---SQL语言的功能
  19. android 监听系统广播
  20. python中pass语句的出现是为了保持程序结构的完整性_pass语句的出现是为了保持程序结构的完整性。( )_学小易找答案...

热门文章

  1. SpringBoot学习:读取yml和properties文件的内容
  2. 关于mysql存储大数据的问题
  3. ANSI,ASCII,Unicode的区别与联系
  4. 了解模型、视图和控制器
  5. 北京.net俱乐部博客园小组成立了
  6. Java 面试必考难点,这一个教程全搞定
  7. linux系统 opt扩容,Linux系统扩容根目录磁盘空间的操作方法
  8. 初识Docker-Docker的安装
  9. 策略模式在JDK 源码中的体现
  10. 数据库-优化-pt-query-digest使用简介