HeavyCalc.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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(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, fn: fn.toString()});
  66. } else {
  67. reject(new Error('Worker does not exist'));
  68. }
  69. });
  70. }
  71. }
  72. //singleton
  73. let instance = null;
  74. class HeavyCalc {
  75. constructor(opts = {}) {
  76. const singleton = opts.singleton || false;
  77. if (singleton && instance)
  78. return instance;
  79. this.threads = opts.threads || 1;
  80. this.terminated = false;
  81. this.workers = [];
  82. this.load = [];
  83. for (let i = 0; i < this.threads; i++) {
  84. const worker = new CalcThread();
  85. this.workers.push(worker);
  86. this.load.push(0);
  87. }
  88. if (singleton) {
  89. instance = this;
  90. }
  91. }
  92. async run(args, fn) {
  93. if (this.terminated || !this.workers.length)
  94. throw new Error('All workers terminated');
  95. //находим поток с минимальной нагрузкой
  96. let found = 0;
  97. for (let i = 1; i < this.load.length; i++) {
  98. if (this.load[i] < this.load[found])
  99. found = i;
  100. }
  101. try {
  102. this.load[found]++;
  103. return await this.workers[found].run(args, fn);
  104. } finally {
  105. this.load[found]--;
  106. }
  107. }
  108. terminate() {
  109. for (let i = 0; i < this.workers.length; i++) {
  110. this.workers[i].terminate();
  111. }
  112. this.workers = [];
  113. this.load = [];
  114. this.terminated = true;
  115. }
  116. }
  117. module.exports = HeavyCalc;