HeavyCalc.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. const { Worker } = require('worker_threads');
  2. class CalcThread {
  3. constructor() {
  4. this.worker = null;
  5. this.listeners = new Map();
  6. this.requestId = 0;
  7. this.runWorker();
  8. }
  9. terminate() {
  10. if (this.worker) {
  11. this.worker.terminate();
  12. for (const listener of this.listeners.values()) {
  13. listener({error: 'Worker terminated'});
  14. }
  15. }
  16. this.worker = null;
  17. }
  18. runWorker() {
  19. const workerProc = () => {
  20. const { parentPort } = require('worker_threads');
  21. const sleep = (ms) => {
  22. return new Promise(resolve => setTimeout(resolve, ms));
  23. };
  24. if (parentPort) {
  25. parentPort.on('message', async(mes) => {
  26. let result = {};
  27. try {
  28. const fn = new Function(`'use strict'; return ${mes.fn}`)();
  29. result.result = await fn(mes.args, sleep);
  30. } catch (e) {
  31. result = {error: e.message};
  32. }
  33. result.requestId = mes.requestId;
  34. parentPort.postMessage(result);
  35. });
  36. }
  37. };
  38. const worker = new Worker(`const wp = ${workerProc.toString()}; wp();`, {eval: true});
  39. worker.on('message', (mes) => {
  40. const listener = this.listeners.get(mes.requestId);
  41. if (listener) {
  42. this.listeners.delete(mes.requestId);
  43. listener(mes);
  44. }
  45. });
  46. worker.on('error', (err) => {
  47. console.error(err);
  48. });
  49. worker.on('exit', () => {
  50. this.terminate();
  51. });
  52. this.worker = worker;
  53. }
  54. //async
  55. run(params) {//args, fn
  56. return new Promise((resolve, reject) => {
  57. this.requestId++;
  58. this.listeners.set(this.requestId, (mes) => {
  59. if (mes.error)
  60. reject(new Error(mes.error));
  61. else
  62. resolve(mes.result);
  63. });
  64. if (this.worker) {
  65. this.worker.postMessage({requestId: this.requestId, args: params.args, fn: params.fn.toString()});
  66. } else {
  67. reject(new Error('Worker does not exist'));
  68. }
  69. });
  70. }
  71. }
  72. class HeavyCalc {
  73. constructor(opts = {}) {
  74. this.threads = opts.threads || 1;
  75. this.singleton = opts.singleton || false;
  76. this.terminated = false;
  77. this.workers = [];
  78. this.load = [];
  79. for (let i = 0; i < this.threads; i++) {
  80. const worker = new CalcThread();
  81. this.workers.push(worker);
  82. this.load.push(0);
  83. }
  84. }
  85. async run(params) {
  86. if (this.terminated || !this.workers.length)
  87. throw new Error('All workers terminated');
  88. //находим поток с минимальной нагрузкой
  89. let found = 0;
  90. for (let i = 1; i < this.load.length; i++) {
  91. if (this.load[i] < this.load[found])
  92. found = i;
  93. }
  94. try {
  95. this.load[found]++;
  96. return await this.workers[found].run(params);
  97. } finally {
  98. this.load[found]--;
  99. }
  100. }
  101. terminate() {
  102. for (let i = 0; i < this.workers.length; i++) {
  103. this.workers[i].terminate();
  104. }
  105. this.workers = [];
  106. this.load = [];
  107. this.terminated = true;
  108. }
  109. }
  110. module.exports = HeavyCalc;