babylon.workerPool.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  2. module BABYLON {
  3. interface WorkerInfo {
  4. worker: Worker;
  5. active: boolean;
  6. }
  7. /**
  8. * Helper class to push actions to a pool of workers.
  9. */
  10. export class WorkerPool implements IDisposable {
  11. private _workerInfos: Array<WorkerInfo>;
  12. private _pendingActions = new Array<(worker: Worker, onComplete: () => void) => void>();
  13. /**
  14. * Constructor
  15. * @param workers Array of workers to use for actions
  16. */
  17. constructor(workers: Array<Worker>) {
  18. this._workerInfos = workers.map(worker => ({
  19. worker: worker,
  20. active: false
  21. }));
  22. }
  23. /**
  24. * Terminates all workers and clears any pending actions.
  25. */
  26. public dispose(): void {
  27. for (const workerInfo of this._workerInfos) {
  28. workerInfo.worker.terminate();
  29. }
  30. delete this._workerInfos;
  31. delete this._pendingActions;
  32. }
  33. /**
  34. * Pushes an action to the worker pool. If all the workers are active, the action will be
  35. * pended until a worker has completed its action.
  36. * @param action The action to perform. Call onComplete when the action is complete.
  37. */
  38. public push(action: (worker: Worker, onComplete: () => void) => void): void {
  39. for (const workerInfo of this._workerInfos) {
  40. if (!workerInfo.active) {
  41. this._execute(workerInfo, action);
  42. return;
  43. }
  44. }
  45. this._pendingActions.push(action);
  46. }
  47. private _execute(workerInfo: WorkerInfo, action: (worker: Worker, onComplete: () => void) => void): void {
  48. workerInfo.active = true;
  49. action(workerInfo.worker, () => {
  50. workerInfo.active = false;
  51. const nextAction = this._pendingActions.shift();
  52. if (nextAction) {
  53. this._execute(workerInfo, nextAction);
  54. }
  55. });
  56. }
  57. }
  58. }