Skip to content

Commit

Permalink
feat: add an article on async and multithreaded
Browse files Browse the repository at this point in the history
  • Loading branch information
altrusl committed Apr 11, 2024
1 parent 06e44c1 commit 2c22cae
Show file tree
Hide file tree
Showing 4 changed files with 609 additions and 564 deletions.
18 changes: 18 additions & 0 deletions docs/en/frontend/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@ At the same time, a good analogy of an object with a global ("static") and local

:::

::: details Multithreading and asynchronicity

**Multithreading** is when a programmer can create a separate thread and run his specific code in it. For example, you can create two threads, one in an infinite loop outputs "Thread A" to the console and the other "Thread B". These strings will alternate in the output. You can prioritize the threads, and then the thread with priority 3 will output messages 3 times more often than the thread with priority 1.

These two threads should be executed simultaneously, but this is conditional. Because if there are 10 threads and the processor is dual-core with two threads per core, it is physically impossible to execute more than 4 simultaneous threads. That's why threads are divided into pieces of code and they are executed one by one - this is called concurrency.

In the JavaScript world, threads can become queued at the JS runtime, OS, CPU level. Common desktop applications (for example, IDEs) can also have good support for parallelization on multi-core processors - and then they use CPUs as efficiently as possible, or load only one core. In the latter case, upgrading to a newer multi-core CPU will do almost nothing if the old and the new one have approximately the same frequency.

**Asynchronicity** is when there is some non-blocking function whose exact execution time is unknown. And the programmer can specify the code to be executed after this function is executed (pass a callback). Promises and async/await are non-trivial but still just convenient wrappers over this logic.

So, with asynchronicity, there is usually some border function that depends on external circumstances (`fetch, nextTick, fs.readdir, setTimeout`). Its "pseudo-parallel" execution in one thread together with the main code is provided by the `Event Loop` mechanism.

Thus, these are completely different things both in purpose and usage. asynchronicity in JavaScript is realized through promises and async/await, multithreading or its similarity is realized by rantime (`Web workers`, `worker_threads`).

Asynchronicity is needed to communicate with the "outside world", including browser rendering. Multithreading allows to separate resource-intensive computations (as well as network requests) into separate threads (`Web workers`), which reduces the load on the main thread, which is responsible for rendering. This has a favorable effect on the responsiveness of your UI.

:::

::: details Useful tips

###### Avoid dependencies
Expand Down
18 changes: 18 additions & 0 deletions docs/ru/frontend/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,24 @@

:::

::: details Многопоточность и асинхронность

**Многопоточность** - это когда программист может создать отдельный поток и запустить в нем свой определенный код. Например, можно создать два потока, один в бесконечном цикле выводит в консоль "*Поток А*", а второй - "*Поток В*". Эти строки будут чередоваться в выводе. Можно задать приоритеты потокам, и тогда поток в приоритетом 3 будет выводить сообщения в 3 раза чаще, чем поток с приоритетом 1.

Данные два потока должны выполняться одновременно, но это условно. Потому что если потоков 10, а процессор двухядерный с двумя своими потоками на ядро, то чисто физически больше 4 одновременных потоков выполнять нельзя. Поэтому потоки делятся на кусочки кода, и они выполняются по очереди - это называется конкурентностью.

В мире JavaScript cтановиться в одну очередь потоки могут на уровне JS рантайма, OS, CPU. Обычные десктопные приложения (например, IDE) тоже бывают с хорошей поддержкой распараллеливания на многоядерные процессоры - и тогда они используют CPU максимально эффективно, или нагружающие только одно ядро. В последнем случае апгрейд процессора на более современный многоядерный почти ничего не даст, если у старого и нового примерно одна частота.

**Асинхронность** - это когда есть некая неблокирующая функция, точное время исполнения которой неизвестно. И программист может указать код, который должен выполниться после исполнения данной функции (передать `callback`). Промисы и `async/await` это нетривиальные, но всё же просто удобные обертки над данной логикой.

Итак, при асинхронности обычно есть некая пограничная функция, зависящая от внешних обстоятельств (`fetch, nextTick, fs.readdir, setTimeout`). Её "псевдопараллельное" исполнение в одном потоке вместе с основным кодом обеспечивается механизмом `Event Loop`.

Таким образом, это абсолютно разные вещи как по целевому назначению, так и по использованию. Асинхронность в JavaScript реализована через промисы и async/await, многопоточность или её подобие реализуется райнтаймом (`Web workers`, `worker_threads`).

Асинхронность нужна для общения с "внешним миром", включая отрисовку браузера. Многопоточность позволяет выделить ресурсоемкие вычисления (а также сетевую загрузку) в отдельные потоки (`Web workers`), что снижает нагрузку на основной поток, который отвечает и за рендеринг. Это благоприятно сказывается на отзывчивости вашего UI.

:::

::: details Полезные советы

###### Избегайте зависимостей
Expand Down
10 changes: 5 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
"vue3-toastify": "^0.1.14"
},
"devDependencies": {
"@antfu/eslint-config": "^2.8.0",
"@antfu/eslint-config": "^2.13.3",
"@vitejs/plugin-vue": "^5.0.4",
"eslint": "^8.57.0",
"sass": "^1.71.1",
"typescript": "^5.4.2",
"vite": "^5.1.5",
"vitepress": "1.0.0-rc.45"
"sass": "^1.74.1",
"typescript": "^5.4.5",
"vite": "^5.2.8",
"vitepress": "^1.1.0"
}
}
Loading

0 comments on commit 2c22cae

Please sign in to comment.