程序员不得不消化的基本概念:线程与协程,并行与并发

这是程序员的基本常识,这都搞不清楚,就不配为码农,就不配混CSDN。为人君者,招聘时可以以此为入门问题。

名词解释

在中文里,并发与并行很难望文生义,从字面上很难了解确切含义,貌似区别不大,但从英文角度看就差别显著了。

  • 线程: thread, 是系统运算调度的最小单位。它被包含在进程之中,是进程中的实际运作单位,是系统中独立运行的基本单位
  • 协程: coroutine,是程序中的一种组件,它允许在设置多个入口点和中断位置,将子程序泛化为非抢占式的多任务处理模式,是用户级线程的一种实现。
  • 并行: Parallelism,Parallelism means that an application splits its tasks up into smaller subtasks which can be processed in parallel, for instance on multiple CPUs at the exact same time.
  • 并发: Concurrency,Concurrency means that an application is making progress on more than one task at the same time (concurrently)

差异理解

协程(Coroutine)编译器级的,进程(Process)和线程(Thread)操作系统级的。也就是说,你可以开发一个协程库,但没法开发线程库,因为线程是操作系统资源,只能是操作系统提供。golang和kotlin语言里天然提供了协程库,Java没有,但借助于nio和线程也能实现。协程最轻量级,开销最小。线程和进程依次之。

协程为并发而生,线程为并行而生。所以关键点是理解并发和并行的差异。

在这里插入图片描述

先看看老外的解释吧:

A system is said to be concurrent if it can support two or more actions in progress at the same time. A system is said to be parallel if it can support two or more actions executing simultaneously.

并发就是多个事情都在“进行中” (in progress),但未必都在执行(may not be executed)
老外补充道:

Meanwhile, multiple actions are simultaneously executed in parallel systems. In fact, concurrency and parallelism are conceptually overlapped to some degree, but “in progress” clearly makes them different.

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.

基本上是说清楚了。用中文总结一下:

  • 并行就是同一时刻我可以做多件事。
  • 并发是某一段时间我可以做多件事。但某一时刻我只能做一件事,可能我在做A,也可能在做B或C,整体效果上看A,B,C三件事情同时在做。多件事穿插进行。
  • 串行就是多个事情是排好序的,流水线方式执行的,未来某个时刻做哪件事是确定的。而并发是不确定的,未来某个时刻做哪件事是随机的,取决于调度程序。

大并发下的最佳实践就是多进程+协程,既充分利用多核,又充分发挥协程的高效率,可获得极高的性能。

参考

猜你喜欢

转载自blog.csdn.net/jgku/article/details/130799795
今日推荐