WorkerPool.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * @author Deepkolos / https://github.com/deepkolos
  3. */
  4. export class WorkerPool {
  5. constructor ( pool = 4 ) {
  6. this.pool = pool;
  7. this.queue = [];
  8. this.workers = [];
  9. this.workersResolve = [];
  10. this.workerStatus = 0;
  11. }
  12. _initWorker ( workerId ) {
  13. if ( !this.workers[ workerId ] ) {
  14. const worker = this.workerCreator();
  15. worker.addEventListener( 'message', this._onMessage.bind( this, workerId ) );
  16. this.workers[ workerId ] = worker;
  17. }
  18. }
  19. _getIdleWorker () {
  20. for ( let i = 0 ; i < this.pool ; i ++ )
  21. if ( ! ( this.workerStatus & ( 1 << i ) ) ) return i;
  22. return -1;
  23. }
  24. _onMessage( workerId, msg ) {
  25. const resolve = this.workersResolve[ workerId ];
  26. resolve && resolve( msg );
  27. if ( this.queue.length ) {
  28. const { resolve, msg, transfer } = this.queue.shift();
  29. this.workersResolve[ workerId ] = resolve;
  30. this.workers[ workerId ].postMessage( msg, transfer );
  31. } else {
  32. this.workerStatus ^= 1 << workerId;
  33. }
  34. }
  35. setWorkerCreator ( workerCreator ) {
  36. this.workerCreator = workerCreator;
  37. }
  38. setWorkerLimit ( pool ) {
  39. this.pool = pool;
  40. }
  41. postMessage ( msg, transfer ) {
  42. return new Promise( ( resolve ) => {
  43. const workerId = this._getIdleWorker();
  44. if ( workerId !== -1 ) {
  45. this._initWorker( workerId );
  46. this.workerStatus |= 1 << workerId;
  47. this.workersResolve[ workerId ] = resolve;
  48. this.workers[ workerId ].postMessage( msg, transfer );
  49. } else {
  50. this.queue.push( { resolve, msg, transfer } );
  51. }
  52. } );
  53. }
  54. dispose () {
  55. this.workers.forEach( ( worker ) => worker.terminate() );
  56. this.workersResolve.length = 0;
  57. this.workers.length = 0;
  58. this.queue.length = 0;
  59. this.workerStatus = 0;
  60. }
  61. }