0
0

WorkerPool.js 1.8 KB

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