NGL@1.0.0-beta.7 Home Manual Reference Source Gallery

src/worker/worker-pool.js

  1. /**
  2. * @file Worker Pool
  3. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  4. * @private
  5. */
  6.  
  7. import Worker from './worker.js'
  8.  
  9. function WorkerPool (name, maxCount) {
  10. maxCount = Math.min(8, maxCount || 2)
  11.  
  12. var pool = []
  13. var count = 0
  14.  
  15. // API
  16.  
  17. this.name = name
  18.  
  19. this.maxCount = maxCount
  20.  
  21. this.post = function (aMessage, transferList, onmessage, onerror) {
  22. var worker = this.getNextWorker()
  23. worker.post(aMessage, transferList, onmessage, onerror)
  24.  
  25. return this
  26. }
  27.  
  28. this.terminate = function () {
  29. pool.forEach(function (worker) {
  30. worker.terminate()
  31. })
  32. }
  33.  
  34. this.getNextWorker = function () {
  35. var nextWorker
  36. var minPending = Infinity
  37.  
  38. for (var i = 0; i < maxCount; ++i) {
  39. if (i >= count) {
  40. nextWorker = new Worker(name)
  41. pool.push(nextWorker)
  42. count += 1
  43. break
  44. }
  45.  
  46. var worker = pool[ i ]
  47.  
  48. if (worker.pending === 0) {
  49. nextWorker = worker
  50. break
  51. } else if (worker.pending < minPending) {
  52. minPending = worker.pending
  53. nextWorker = worker
  54. }
  55. }
  56.  
  57. return nextWorker
  58. }
  59.  
  60. Object.defineProperties(this, {
  61. count: {
  62. get: function () { return count }
  63. }
  64. })
  65. }
  66.  
  67. WorkerPool.prototype.constructor = WorkerPool
  68.  
  69. export default WorkerPool