nodejs에서 스레드를 만드는 방법
한 번에 여러 메서드를 실행하기위한 스레드를 만드는 방법이 있습니까?
이렇게하면 다른 모든 스레드 사이에 어떤 메서드가 실패하면 종료됩니다.
모든 node.js 프로세스는 설계 상 단일 스레드입니다. 따라서 여러 스레드를 얻으려면 여러 프로세스가 있어야합니다 (다른 포스터에서 지적했듯이 Node에서 스레드로 작업 할 수있는 기능을 제공하는 링크 할 수있는 라이브러리도 있지만 해당 라이브러리 없이는 그러한 기능이 존재하지 않습니다) . Shawn Vincent의 답변 참조 https://github.com/audreyt/node-webworker-threads )
node.js 문서 ( http://nodejs.org/api/child_process.html) 에 표시된대로 기본 프로세스에서 하위 프로세스를 시작할 수 있습니다 . 예제는이 페이지에서 꽤 훌륭하고 매우 간단합니다.
그런 다음 부모 프로세스는 시작된 모든 프로세스에서 닫기 이벤트를 감시 한 다음 시작된 다른 프로세스를 강제 종료하여 하나의 실패한 모든 중지 전략을 달성 할 수 있습니다.
참조 : 멀티 코어 머신의 Node.js
또한 Node.js 내에서 네이티브 스레딩을 수행하기위한 라이브러리가 하나 이상 있습니다. node-webworker-threads
https://github.com/audreyt/node-webworker-threads
이것은 기본적으로 node.js 용 Web Worker 브라우저 API 를 구현합니다.
Node 10.5부터는 다중 스레딩 지원 이 있지만 실험적 입니다. 곧 안정되기를 바랍니다.
다음 리소스 확인 :
- PR 스레드 .
- 공식 문서
- 블로그 기사 : Node 10.5.0의 스레드 : 실용적인 소개
업데이트 :
Node v11.7.0 부터는 --experimental-worker
플래그 를 사용할 필요가 없습니다 .
릴리스 노트 : https://nodejs.org/en/blog/release/v11.7.0/
Napa.js를 사용하여 멀티 스레딩을 얻을 수 있습니다.
https://github.com/Microsoft/napajs
"Napa.js는 V8에 구축 된 다중 스레드 JavaScript 런타임으로, 원래 Bing에서 성능 저하가없는 고도로 반복적 인 서비스를 개발하도록 설계되었습니다. 발전함에 따라 CPU 바인딩 작업에서 Node.js를 보완하는 것이 유용하다는 것을 알게되었습니다. , 여러 V8 분리에서 JavaScript를 실행하고 이들간에 통신 할 수있는 기능이 있습니다. Napa.js는 Node.js 모듈로 노출되며 Node.js 종속성없이 호스트 프로세스에 임베드 될 수도 있습니다. "
Rx를 사용하는 경우 rxjs-cluster에 플러그인하여 작업을 병렬 실행으로 분할하는 것이 다소 간단합니다. (면책 조항 : 저자입니다)
https://www.npmjs.com/package/rxjs-cluster
프로젝트 상태에 대해 잘 모르겠지만 이제 https://github.com/xk/node-threads-a-gogo 도 있습니다 .
Node.js에서 실제 멀티 스레딩이 필요 했고 저에게 효과 가 있었던 것은 스레드 패키지였습니다. 자체 Node.js 메시지 루프가있는 다른 프로세스를 생성하므로 서로를 차단하지 않습니다. 설정이 쉽고 설명서를 통해 빠르게 준비하고 실행할 수 있습니다. 메인 프로그램과 워커는 양방향으로 통신 할 수 있으며 필요한 경우 워커 "스레드"를 종료 할 수 있습니다.
멀티 스레딩과 Node.js는 복잡하고 광범위하게 논의되는 주제이기 때문에 내 특정 요구 사항에 맞는 패키지를 찾는 것이 매우 어려웠습니다 . 기록을 위해 이들은 나를 위해 작동하지 않았습니다 .
- small-worker는 워커 생성을 허용했지만 동일한 메시지 루프를 공유하는 것처럼 보였습니다 (하지만 제가 뭔가 잘못했을 수도 있습니다. 스레드 가 더 많은 문서를 통해 실제로 여러 프로세스를 사용 했으므로 작동 할 때까지 계속 진행했습니다)
- webworker-threads 는
require
내가 필요한 작업자에서 -ing 모듈을 허용하지 않았습니다.
그리고 내가 진짜 멀티 스레딩이 필요한 이유를 묻는 사람들을 위해 : Raspberry Pi 및 인터럽트와 관련된 애플리케이션의 경우. 한 스레드는 이러한 인터럽트를 처리하고 다른 스레드는 데이터 저장을 처리합니다.
NodeJS는 이제 스레드를 포함 합니다 (응답시 실험적 기능으로).
You might be looking for Promise.race
(native I/O racing solution, not threads)
Assuming you (or others searching this question) want to race threads to avoid failure and avoid the cost of I/O operations, this is a simple and native way to accomplish it (which does not use threads). Node is designed to be single threaded (look up the event loop), so avoid using threads if possible. If my assumption is correct, I recommend you use Promise.race
with setTimeout
(example in link). With this strategy, you would race a list of promises which each try some I/O operation and reject the promise if there is an error (otherwise timeout). The Promise.race
statement continues after the first resolution/rejection, which seems to be what you want. Hope this helps someone!
The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.
You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using --experimental-worker when invoking Node.js.
Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1
//package.json
"scripts": {
"start": "node --experimental-modules --experimental- worker index.mjs"
},
Now, you need to import Worker from worker_threads. Note: You need to declare you js files with '.mjs' extension for ES6 support.
//index.mjs
import { Worker } from 'worker_threads';
const spawnWorker = workerData => {
return new Promise((resolve, reject) => {
const worker = new Worker('./workerService.mjs', { workerData });
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with
exit code ${code}`)));
})
}
const spawnWorkers = () => {
for (let t = 1; t <= 5; t++)
spawnWorker('Hello').then(data => console.log(data));
}
spawnWorkers();
Finally, we create a workerService.mjs
//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';
// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);
Output:
npm run start
Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5
Node.js doesn't use threading. According to its inventor that's a key feature. At the time of its invention, threads were slow, problematic, and difficult. Node.js was created as the result of an investigation into an efficient single-core alternative. Most Node.js enthusiasts still cite ye olde argument as if threads haven't been improved over the past 50 years.
As you know, Node.js is used to run JavaScript. The JavaScript language has also developed over the years. It now has ways of using multiple cores - i.e. what Threads do. So, via advancements in JavaScript, you can do some multi-core multi-tasking in your applications. user158 points out that Node.js is playing with it a bit. I don't know anything about that. But why wait for Node.js to approve of what JavaScript has to offer.
Google for JavaScript multi-threading instead of Node.js multi-threading. You'll find out about Web Workers, Promises, and other things.
참고URL : https://stackoverflow.com/questions/18613023/how-to-create-threads-in-nodejs
'programing tip' 카테고리의 다른 글
matplotlib의 그림 내에서 각 플롯 된 선에 대해 새 색상을 선택하는 방법은 무엇입니까? (0) | 2020.09.14 |
---|---|
균형 잡힌 나무의 정의 (0) | 2020.09.14 |
Git : 단일 수정 오류가 필요함 (0) | 2020.09.14 |
R의 벡터에 고유 한 값 나열 (0) | 2020.09.14 |
PHP에서 클래스 이름을 어떻게 얻습니까? (0) | 2020.09.14 |