Dev pool error exit что это значит
Перейти к содержимому

Dev pool error exit что это значит

  • автор:

Разгон antminer L3

ПРОШИВКА VNISH ДЛЯ РАЗГОНА И ДАУНВОЛЬТА ANTMINER L3+ L3++

ОФИЦИАЛЬНАЯ ПРОШИВКА VNISH

ВНИМАНИЕ : Прошивка подходит на все асики Antminer L3 +/ L3++

Релиз 3.9.1

Исправили ошибку dev fee pool error.

Исправили мелкие ошибки.

Исправили ошибку фана при низких оборотах.

Исправили ошибку функции поиска асика на ферме.

Добавлена опция отель фии (где вы можете перенаправлять часть мощностей на оплату электричества, размещения оборудования или оплату за обслуживания майнеров)
Добавили функцию Find Miner в конфиг мультипликатор для поиска большего количество майнеров сразу.

ВНИМАНИЕ : Прошивка подходит на все асики Antminer L3 +/ L3++

Если при смене прошивки BITMAIN вы видите сообщение: can not find signature

Это означает что на вашем оборудовании установлена прошивка BITMAIN 2019 года, в которой установлена защита от перезаписи, прошивки 2018 года не имеют данной защиты.

Если у вас установлена прошивка BITMAIN 2019 года установка прошивки vnish возможна через файл снятие сигнатуры или только через SD карту (Архивы выложены на сайте, необходимо скачать архив, распаковать и прочитать инструкцию)

Если в процессе установки прошивки через SD карту зеленая и красная лампы на контрольной плате не моргают и прошивка не устанавливается проверьте правильно ли вы записали SD образ согласно инструкции, то есть вероятность, что ваш асик заражен вирусом и он заблокировал возможность апгрейда на любые другие прошивки, необходимо использовать руководство для лечения вирусов . Рекомендуем всегда менять стандартный пароль root на любой другой и отключать порт ssh, это можно сделать массово при помощи нашей прошивки.

Dev pool error exit что это значит

11:00 — 20:00
Воскресенье выходной

ВАША КОРЗИНА

https://pro-miner.ru/ /cart/view.html /catalog/product/view.html /cart/delete.html https://pro-miner.ru/components/com_jshopping/files/img_products 2 ✔ Товар в корзине Товар добавлен в корзину Перейти в корзину Удалить Товаров: на сумму Не заданы дополнительные параметры

navigation

  • Главная
  • Каталог
  • ПРОШИВКИ
  • BITMAIN
  • Прошивка для Antminer S9 (разгон до 22 TH/s)

После обновления сервера выдает сообщение что не сконфигурирован серверный пул.

Сегодня запустил обновление виртуальной машины (в меню пункт 19). Все сработало и при следующем входе система предложила обновиться до версии 5.0. что и было запущено. Так же все вроде без проблем.
Сейчас при входе программа начала выдавать следующее сообщение:

В действительности сайт всего 1 и никакого пула или распределения у нас нет.
Что делать в данном случае?

Сообщений: 2764 Баллов: 449 Регистрация: 20.04.2008
АКРИТ Веб-студия
16.06.2014 20:17:01
создать пул с одним сервером и все заработает.
Веб-студия АКРИТ Увеличьте продажи трансформировав сайт в сеть торговых точек в интернете
Заглянувший
Сообщений: 20 Баллов: 1 Регистрация: 07.12.2013
16.06.2014 20:45:12

Тогда второй вопрос — а как создать пул, если система показывает только единственный вариант «0. exit» ?
Создать из командной строки можно?

Сообщений: 2764 Баллов: 449 Регистрация: 20.04.2008
АКРИТ Веб-студия
16.06.2014 21:12:38
перезагрузит сервер и должно появиться стартовое меню из трех пунктов.
Веб-студия АКРИТ Увеличьте продажи трансформировав сайт в сеть торговых точек в интернете
Заглянувший
Сообщений: 20 Баллов: 1 Регистрация: 07.12.2013
16.06.2014 21:26:56
Пробовал, но меню не меняется.
Попробую сегодня еще раз глубокой ночью.
Заглянувший
Сообщений: 23 Баллов: 2 Регистрация: 28.02.2008
22.06.2014 23:51:46

Алексей Титов, не знаю, решили или нет, но на всякий случай отпишу.
Была та же проблема, вылезала эта страница с одним вариантом «0. Exit»

Сегодня «выбрал» пункт 1 (хоть его и не было в меню) – появилась знакомая менюшка, продолжил работу дальше 🙂

Заглянувший
Сообщений: 20 Баллов: 1 Регистрация: 07.12.2013
24.06.2014 13:18:53

Действительно. нажал 1 и сформировался пул и появилась менюшка.

Available actions:
0. Exit
Enter selection: 1
Created sshkey — /etc/ansible/.ssh/***********.bxkey
CREATE_POOL complete: Press ENTER for exit:
Bitrix virtual appliance version 5.0.37
Pool Configuration manager on this host
Found next servers in the pool:
————————————————————————————
ServerName | NetAddress | Conn | Ver | Passwords | Uid | Roles
————————————————————————————
vm********** | 127.0.0.1 | Y | 5.0-37 | ok | 501 | mgmt,mysql_master_1,web
————————————————————————————
Available actions:
1. Manage Hosts in the pool
2. Manage localhost
3. Configure MySQL servers
4. Configure memcahed servers
5. Background tasks in the pool
6. Manage sites in the pool
7. Manage sphinx in the pool
8. Manage web nodes in the pool
9. Monitoring in pool
0. Exit
Enter selection:

Спасибо за подсказку.

Заглянувший
Сообщений: 9 Регистрация: 12.05.2009
26.06.2014 16:03:30

А вот у меня что-то пошло не так. Выбрал 1
CREATE_POOL complete: Press ENTER for exit:
Нажал ENTER и все. завис, затем вышло сообщение Network error: No route to host
Теперь не могу зайти на сервер ни ftp, ни ssh, вообще ни как. Putty пишет «Network error: No route to host».

Заглянувший
Сообщений: 3 Регистрация: 05.08.2014
05.08.2014 09:08:35

Всем добрый день!

Аналогичная проблема.
При выборе варианта 1 сообщает Not found running interfaces on host.

При этом интерфейс есть, веб-доступ работает и даже корп. портал установился без проблем.

Заглянувший
Сообщений: 3 Регистрация: 29.11.2013
22.08.2014 11:06:12

установили чистую машину BitrixVM, в сети нет DHCP — и всё, меню с одним пунктом «0. Exit», непонятно что делать дальше.

Заглянувший
Сообщений: 3 Регистрация: 29.11.2013
22.08.2014 11:07:13
Гениально, блин! Надо нажать «2»
Заглянувший
Сообщений: 3 Регистрация: 29.11.2013
22.08.2014 11:09:09

Забава продолжается — при выборе тайного меню под «2», нельзя настраивать сетевые интерфейсы — их просто нет в списке.

Заглянувший
Сообщений: 8 Регистрация: 31.03.2011
01.10.2014 12:40:53

Цитата
Евгения Николова пишет:
Забава продолжается — при выборе тайного меню под «2», нельзя настраивать сетевые интерфейсы — их просто нет в списке.

Такая же ерунда. Кто-нибудь разобрался что делать дальше-то с этими проблемами?
Сообщений: 1126 Баллов: 569 Регистрация: 23.03.2005
20.10.2014 14:31:22

Проблема в том, что по умолчанию Веб-окружение Битрикс настроено на использование адаптера сети eth0.
При старте виртуальной машины, адаптер может измениться и быть eth1, eth2 и т.д.
Поэтому смотрим ваш MAC адаптера, идем в /etc/udev/rules.d/70-persistent-net.rules и оставляем там только его и обзываем его как eth0.
После этого перезапускаем виртуальную машину и все должно заработать.

студия Leveret
Заглянувший
Сообщений: 12 Баллов: 1 Регистрация: 16.01.2014
21.10.2014 11:10:22

Цитата
Анатолий Зайчёнок пишет:
Проблема в том, что по умолчанию Веб-окружение Битрикс настроено на использование адаптера сети eth0.
При старте виртуальной машины, адаптер может измениться и быть eth1, eth2 и т.д.
Поэтому смотрим ваш MAC адаптера, идем в /etc/udev/rules.d/70-persistent-net.rules и оставляем там только его и обзываем его как eth0.
После этого перезапускаем виртуальную машину и все должно заработать.

поменял через vi название и мак

Сообщений: 1126 Баллов: 569 Регистрация: 23.03.2005
21.10.2014 11:59:02
70-persistent-net.rules покажите
студия Leveret
Заглянувший
Сообщений: 12 Баллов: 1 Регистрация: 16.01.2014
21.10.2014 14:06:07

Цитата
Анатолий Зайчёнок пишет:
70-persistent-net.rules покажите

Сообщений: 1126 Баллов: 569 Регистрация: 23.03.2005
21.10.2014 15:34:46
Сервер перезагружали?
После логина нужно нажать 1, создать пул сначала.
студия Leveret
Заглянувший
Сообщений: 12 Баллов: 1 Регистрация: 16.01.2014
22.10.2014 06:18:05

Да, да, уже все перепробовал ((
Кстати возможно это важно — виртуалка на hyper-v
http://joxi.ru/lJ2b5MQ4SKpgm6

Даже машину импортировал еще раз пробовал.

Посетитель
Сообщений: 52 Баллов: 4 Регистрация: 21.07.2011
22.10.2014 09:20:14

Проверьте наличие конфигурационных файлов сетевых интерфейсов.
/etc/sysconfig/network-scripts/ifcfg-eth0
Есть этот файлик?
Какое его содержимое?
Макс адрес 70-persistent-net.rules совпадает с мак адресом сетевой карты в гипервизоре?

Посетитель
Сообщений: 53 Баллов: 4 Регистрация: 30.10.2014
30.10.2014 15:35:28

  1. Не использовать тип Gen2 при создании VM с линуксом (пока, по крайней мере) — ник чему хорошему это в дальнейшем не приведет.
  2. При создании VM не назначать никакого сетевого интерфейса, а после создания добавить Legacy Network Adapter (а не обычный Network Adapter)
  3. Для сетевого адаптера в конфигурации VM явно указать MAC-адрес (не использовать пул)
  4. Включить все компоненты интеграции для VM (если ядро свежее, то они туда и так включены и будут задействованы, если ядро старое, то вреда все равно не будет)
  5. Динамическую память использовать можно, но будет зависеть от версии ядра и приложений. Для виртуалки с Битриксом по опыту лучше дать статику.
  6. В /etc/grub.conf для всех kernel-записей добавить параметр elevator=noop — позволит избежать «просадки» дисковой производительности VM.
  7. Дисковое пространство расширять стандартными средствами Hyper-V, внутри VM разделы расширять также стандартными средствами Linux — fdisk, pvresize, lvextend, resize2fs

Заглянувший
Сообщений: 1 Регистрация: 26.11.2014
26.11.2014 09:19:03

Здравствуйте коллеги.
Столкнулся с этой же проблемой. Корпоративный портал поднят на виртуальной машине битрикс VMware.
Решение оказалось довольно простым:
1. Удаляем виртуальный сетевой адаптер в настройках машины и добавляем новый.
2. Нажимаем циферку «2» и создаем Пул серверов.
Всё работает.
Надеюсь кому поможет.

Заглянувший
Сообщений: 5 Регистрация: 16.05.2014
06.12.2014 11:07:48

Цитата
ВолгаТЭКинжиниринг написал:
1. Удаляем виртуальный сетевой адаптер в настройках машины и добавляем новый.
2. Нажимаем циферку «2» и создаем Пул серверов.

Можно поподробнее, для «чайников»? Как удалить сетевой адаптер? сегодня скачала новую версию ВМ — VMBitrix5.0.46-vmware — результат запуска виден на картинке. Старая версия ВМ тоже не работает, выдает ошибку при открытии сайта.

Заглянувший
Сообщений: 1 Регистрация: 17.11.2013
25.12.2014 09:44:22
Вопрос еще актуален. Тоже прошу подсказать как удалить сетевой адаптер?
Администратор
Сообщений: 1232 Баллов: 106 Регистрация: 27.11.2007
25.12.2014 11:22:03

Цитата
Роман Аяпергенов написал:
Вопрос еще актуален. Тоже прошу подсказать как удалить сетевой адаптер?

у вас BitrixVM или BitrixEnv ?
Страницы: 1 2 След.

Продукты

Управление сайтом
Битрикс24
Интернет-магазин + CRM

Решения

Для интернет-магазинов
Каталог готовых решений

Внедрение

Выбрать партнера
Проверить партнера
Стать партнером

1С-Битрикс http://www.1c-bitrix.ru Общие вопросы info@1c-bitrix.ru Приобретение и лицензирование продуктов : sales@1c-bitrix.ru Маркетинг/мероприятия/PR marketing@1c-bitrix.ru Партнерская программа partners@1c-bitrix.ru Мы работаем с 10:00 до 19:00 по московскому времени. Офис в Москве 127287 Россия Московская область Москва 2-я Хуторская улица дом 38А строение 9 Офис в Калининграде +7 (4012) 51-05-64 Офис в Калининграде 236001 Россия Калининградская область Калининград Московский проспект 261 Офис в Киеве ukraine@1c-bitrix.ru Телефон в Киеве +3 (8044)221-55-33 Офис в Киеве 01033 Украина Калининградская область Киев улица Шота Руставели 39/41 офис 1507

Контент для лиц от 16 лет и старше

© 2001-2023 «Битрикс», «1С-Битрикс». Работает на 1С-Битрикс: Управление сайтом. Политика конфиденциальности

Node.js multithreading: Worker threads and why they matter

Node.js multithreading: What are Worker threads and why do they matter?

Editor’s note: This post was updated on 18 January 2022 to include some new information about the Web Workers API and web workers in general, improve and add definitions of key terms, and reflect stable support for the worker_threads module.

Since the release of Node.js v10.5.0, there’s a new worker_threads module available, which has been stable since Node.js v12 LTS.

What exactly is this Worker thread module, and why do we need it? In this post, we will discuss Worker threads alongside:

  • The historical reasons concurrency is implemented in JavaScript and Node.js
  • The problems we might find and their current solutions
  • The future of parallel processing with Worker threads

The history of single-threaded JavaScript

JavaScript was conceived as a single-threaded programming language that ran in a browser. Being single-threaded means that only one set of instructions is executed at any time in the same process (the browser, in this case, or just the current tab in modern browsers).

This made things easier for developers because JavaScript was initially a language that was only useful for adding interaction to webpages, form validations, and so on — nothing that required the complexity of multithreading.

Ryan Dahl saw this limitation as an opportunity when he created Node.js. He wanted to implement a server-side platform based on asynchronous I/O to avoid a need for threads and make things a lot easier.

But concurrency can be a very hard problem to solve. Having many threads accessing the same memory can produce race conditions that are very hard to reproduce and fix.

Is Node.js single-threaded?

Our Node.js applications are only sort of single-threaded, in reality. We can run things in parallel, but we don’t create threads or sync them. The virtual machine and the operating system run the I/O in parallel for us, and when it’s time to send data back to our JavaScript code, it’s the JavaScript that runs in a single thread.

In other words, everything runs in parallel except for our JavaScript code. Synchronous blocks of JavaScript code are always run one at a time:

let flag = false function doSomething() < flag = true // More code (that doesn't change `flag`). // We can be sure that `flag` here is true. // There's no way another code block could have changed // `flag` since this block is synchronous. >

This is great if all we do is asynchronous I/O. Our code consists of small portions of synchronous blocks that run fast and pass data to files and streams, so our JavaScript code is so fast that it doesn’t block the execution of other pieces of JavaScript.

A lot more time is spent waiting for I/O events to happen than JavaScript code being executed. Let’s see this with a quick example:

db.findOne('SELECT . LIMIT 1', function(err, result) < if (err) return console.error(err) console.log(result) >) console.log('Running query') setTimeout(function() < console.log('Hey there') >, 1000)

Maybe this database query takes a minute, but the “Running query” message will be shown immediately after invoking the query. And we will see the “Hey there” message a second after invoking the query regardless of whether the query is still running or not.

Our Node.js application just invokes the function and does not block the execution of other pieces of code. It will get notified through the callback when the query is done, and we will receive the result.

The need for threads to perform CPU-intensive tasks

What happens if we need to do synchronous-intense stuff, such as making complex calculations in memory in a large dataset? Then we might have a synchronous block of code that takes a lot of time and will block the rest of the code.

Imagine that a calculation takes 10 seconds. If we are running a web server, that means that all of the other requests get blocked for at least 10s because of that calculation. That’s a disaster; anything more than 100ms could be too much.

JavaScript and Node.js were not meant to be used for CPU-bound tasks. Since JavaScript is single-threaded, this will freeze the UI in the browser and queue any I/O events in Node.js.

Over 200k developers use LogRocket to create better digital experiences

Learn more →

Going back to our previous example, imagine we now have a query that returns a few thousand results and we need to decrypt the values in our JavaScript code:

db.findAll('SELECT . ', function(err, results) < if (err) return console.error(err) // Heavy computation and many results for (const encrypted of results) < const plainText = decrypt(encrypted) console.log(plainText) >>)

We will get the results in the callback once they are available. Then, no other JavaScript code is executed until our callback finishes its execution.

Usually, as we said before, the code is minimal and fast enough, but in this case, we have many results and we need to perform heavy computations on them. This might take a few seconds, and any other JavaScript execution will be queued during that time, which means we might be blocking all our users during that time if we are running a server in the same application.

Why we will never have multithreading in JavaScript

So, at this point, many people might think our solution should be to add a new module in the Node.js core and allow us to create and sync threads.

But that isn’t possible.If we add threads to JavaScript, then we are changing the nature of the language. We cannot just add threads as a new set of classes or functions available — we’d probably need to change the language to support multithreading. Languages that currently support it have keywords such as synchronized in order to enable threads to cooperate.

It’s a shame we don’t have a nice way of solving this use case in a mature server-side platform such as Node.js. In Java, for example, even some numeric types are not atomic; if you don’t synchronize their access, you could end up having two threads change the value of a variable.

The result would be that, after both threads have accessed the variable, it has a few bytes changed by one thread and a few bytes changed by the other thread — and, thus, will not result in any valid value.

The naive solution: Synchronous code-splitting

Node.js won’t evaluate the next code block in the event queue until the previous one has finished executing. So, one simple thing we can do is split our code into smaller synchronous code blocks and call setImmediate(callback) to tell Node.js we are done. This way, it can continue executing things that are pending in the queue; or, in other words, it can move on to the next iteration (or “tick”) of the event loop.

Let’s see how we can refactor some code from our previous example to take advantage of this. Imagine we have a large array that we want to process, and every item in the array requires CPU-intensive processing:

const arr = [/*large array*/] for (const item of arr) < // do heavy stuff for each item on the array >// code that runs after the whole array is executed

Like we said before, if we do this, it will take too much time to process the whole array and the rest of the JavaScript execution will be blocked. Let’s split this into smaller chunks and use setImmediate(callback) :

const crypto = require('crypto') const arr = new Array(200).fill('something') function processChunk() < if (arr.length === 0) < // code that runs after the whole array is executed >else < console.log('processing chunk'); // pick 10 items and remove them from the array const subarr = arr.splice(0, 10) for (const item of subarr) < // do heavy stuff for each item on the array doHeavyStuff(item) >// Put the function back in the queue setImmediate(processChunk) > > processChunk() function doHeavyStuff(item) < crypto.createHmac('sha256', 'secret').update(new Array(10000).fill(item).join('.')).digest('hex') >// This is just for confirming that we can continue // doing things let interval = setInterval(() => < console.log('tick!') if (arr.length === 0) clearInterval(interval) >, 0)

Now, we can process 10 items each time the event loop runs and call setImmediate(callback) so that if there’s something else the program needs to do, it will do it in between those chunks of 10 items. I’ve added a setInterval() for demonstrating exactly that.

More great articles from LogRocket:

  • Don’t miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket’s Galileo cuts through the noise to proactively resolve issues in your app
  • Use React’s useEffect to optimize your application’s performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

As you can see, the code gets more complicated. And many times, the algorithm is a lot more complex than this, so it’s hard to know where to put the setImmediate() to find a good balance. Besides, the code now is asynchronous, and if we depend on third-party libraries, we might not be able to split the execution into smaller chunks.

Running parallel processes in the background, without threads

So, setImmediate() is sufficient for some simple use cases, but it’s far from an ideal solution. Can we do parallel processing without threads? Yes!

What we need is some kind of background processing, a way of running a task with input that could use whatever amount of CPU and time it needs to return a result back to the main application. Something like this:

// Runs `script.js` in a new environment without sharing memory. const service = createService('script.js') // We send an input and receive an output service.compute(data, function(err, result) < // result available here >)

The reality is that we can already do background processing in Node.js: we can fork the process and do exactly that using message passing, which you can imagine as simply as passing a message from one process to another. This achieves the following goals:

  • The main process can communicate with the child process by sending and receiving events
  • No memory is shared
  • All the data exchanged is “cloned,” meaning that changing it in one side doesn’t change it on the other side
  • If we don’t share memory, we don’t have race conditions, and we don’t need threads!

Well, hold on. This is a solution, but it’s not the ideal solution. Forking a process is expensive and slow — it means running a new virtual machine from scratch and using a lot of memory, since processes don’t share memory.

Can we reuse the same forked process? Sure, but sending different heavy, synchronously-executed workloads inside the forked process creates two problems:

  1. You may not blocking the main app, but the forked process will only be able to process one task at a time
  2. If one task crashes the process, it will leave all tasks sent to the same process unfinished

If you have two tasks — one that will take 10s and one that will take 1s , in that order — it’s not ideal to have to wait 10s to execute the second task. It’s even less ideal if that task never reaches execution because another process got in its way.

Since we are forking processes, we want to take advantage of our OS’s scheduling and all the cores of our machine. The same way you can listen to music and browse the internet at the same time, you can fork two processes and execute all the tasks in parallel.

In order to fix these problems, we need multiple forks, not only one. But we need to limit the number of forked processes because each one will have all the virtual machine code duplicated in memory, meaning a few MBs per process and a non-trivial boot time.

Using worker-farm to pool threads

Like with database connections, we need a pool of processes that are ready to be used, run a task at a time in each one, and reuse the process once the task has finished. This looks complex to implement, and it would be if we were building it from scratch!

Let’s use worker-farm to help us out instead:

// main app const workerFarm = require(‘worker-farm’) const service = workerFarm(require.resolve(‘./script’)) service(‘hello’, function (err, output) < console.log(output) >) // script.js // This will run in forked processes module.exports = (input, callback) =>

So, problem solved? Well, while we have solved the problem, we are still using a lot more memory than a multithreaded solution.

Threads are still very lightweight in terms of resources compared to forked processes. This is the reason why Worker threads were born.

What are Worker threads?

Worker threads have isolated contexts. They exchange information with the main process using message passing, so we avoid the race conditions problem regular threads have! But they do live in the same process, so they use a lot less memory.

You can share memory with Worker threads and pass ArrayBuffer or SharedArrayBuffer objects that are specifically meant for that. Only use them if you need to do CPU-intensive tasks with large amounts of data. Some examples of CPU-intensive tasks with Node workers are discussed in this article. They allow you to avoid a need for data serialization.

Using Worker threads for multiple tasks

You can start using the worker_threads module today if you run Node.js ≥ v10.5.0. If you’re using any version ≤ 11.7.0, however, you need to enable it by using the —experimental-worker flag when invoking Node.js.

Keep in mind that creating a Worker — even though it’s a lot cheaper than forking a process — can also use too many resources depending on your needs. In that case, the docs recommend you create a pool of Workers.

You can probably look for a generic pool implementation or a specific one in npm instead of creating your own pool implementation. Node.js provides AsyncResource to provide proper async tracking of a worker pool.

Let’s see a simple example. First, we’ll implement the main file, create a Worker thread, and give it some data. The API is event-driven, but I’m going to wrap it into a promise that resolves in the first message received from the Worker:

// index.js // run with node --experimental-worker index.js on Node.js 10.x const < Worker >= require('worker_threads') function runService(workerData) < return new Promise((resolve, reject) =>< const worker = new Worker('./service.js', < workerData >); worker.on('message', resolve); worker.on('error', reject); worker.on('exit', (code) => < if (code !== 0) reject(new Error(`Worker stopped with exit code $`)); >) >) > async function run() < const result = await runService('world') console.log(result); >run().catch(err => console.error(err))

As you can see, this is as easy as passing the filename as an argument and the data we want the Worker to process. Remember that this data is cloned and is not in any shared memory.

When we’re finished, we wait for the Worker thread to send us a message by listening to the message event. Implement the service:

const < workerData, parentPort >= require('worker_threads') // You can do any heavy stuff here, in a synchronous way // without blocking the "main thread" parentPort.postMessage(< hello: workerData >)

Here, we need two things: the workerData that the main app sent to us and a way to return information to the main app. This is done with the parentPort that has a postMessage method where we will pass the result of our processing.

That’s it! This is the simplest example, but we can yet build more complex things — for example, we could send multiple messages from the Worker thread indicating the execution status if we need to provide feedback.

Or we can send partial results. Imagine that you are processing thousands of images. Maybe you want to send a message per image processed, but you don’t want to wait until all of them are processed.

In order to run the example, remember to use the —experimental-worker flag if you are using any version prior to Node.js 11.7:

node --experimental-worker index.js

For additional information, check out the worker_threads documentation .

What is the Web Workers API?

Maybe you’ve heard of the Web Workers API. The API is different from worker_threads because the needs and technical conditions are different, but they can solve similar problems in the browser runtime.

The Web Workers API is more mature and is well supported by modern browsers. It can be useful if you are doing crypto mining, compressing/decompressing, image manipulation, computer vision (e.g., face recognition), etc. in your web application.

Introducing: Partytown

Web workers can also be used to run third-party scripts. Running heavy scripts from the main thread can cause UX issues on your site, which isn’t ideal, but running a script apart from the main thread can create issues, as we directly don’t have access to the main thread APIs like window , document , or localStorage .

Here’s where Partytown comes in. Partytown is a lazy-loaded, 6kB package that helps you solve the issue mentioned. Your third-party packages will run as expected without affecting the main thread. If you’re interested in trying this out, see our other post exploring the library, or check out their documentation for a more in-depth discussion.

Conclusion

worker_threads is an exciting and useful module if you need to do CPU-intensive tasks in your Node.js application. They provide the same behavior as threads without sharing memory and, thus, avoid the potential race conditions threads introduce. Since the worker_threads module became stable in Node.js v12 LTS, you should feel secure using it in production-grade apps!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *