|  | 
|  | 1 | +'use strict'; | 
|  | 2 | + | 
|  | 3 | +const common = require('../common.js'); | 
|  | 4 | +const path = require('path'); | 
|  | 5 | +const bench = common.createBenchmark(main, { | 
|  | 6 | +  workers: [1], | 
|  | 7 | +  payload: ['string', 'object'], | 
|  | 8 | +  sendsPerBroadcast: [1, 10], | 
|  | 9 | +  n: [1e5] | 
|  | 10 | +}, { flags: ['--experimental-worker'] }); | 
|  | 11 | + | 
|  | 12 | +const workerPath = path.resolve(__dirname, '..', 'fixtures', 'echo.worker.js'); | 
|  | 13 | + | 
|  | 14 | +function main(conf) { | 
|  | 15 | +  const { Worker } = require('worker'); | 
|  | 16 | + | 
|  | 17 | +  const n = +conf.n; | 
|  | 18 | +  const workers = +conf.workers; | 
|  | 19 | +  const sends = +conf.sendsPerBroadcast; | 
|  | 20 | +  const expectedPerBroadcast = sends * workers; | 
|  | 21 | +  var payload; | 
|  | 22 | +  var readies = 0; | 
|  | 23 | +  var broadcasts = 0; | 
|  | 24 | +  var msgCount = 0; | 
|  | 25 | + | 
|  | 26 | +  switch (conf.payload) { | 
|  | 27 | +    case 'string': | 
|  | 28 | +      payload = 'hello world!'; | 
|  | 29 | +      break; | 
|  | 30 | +    case 'object': | 
|  | 31 | +      payload = { action: 'pewpewpew', powerLevel: 9001 }; | 
|  | 32 | +      break; | 
|  | 33 | +    default: | 
|  | 34 | +      throw new Error('Unsupported payload type'); | 
|  | 35 | +  } | 
|  | 36 | + | 
|  | 37 | +  const workerObjs = []; | 
|  | 38 | + | 
|  | 39 | +  for (var i = 0; i < workers; ++i) { | 
|  | 40 | +    const worker = new Worker(workerPath); | 
|  | 41 | +    workerObjs.push(worker); | 
|  | 42 | +    worker.on('online', onOnline); | 
|  | 43 | +    worker.on('message', onMessage); | 
|  | 44 | +  } | 
|  | 45 | + | 
|  | 46 | +  function onOnline() { | 
|  | 47 | +    if (++readies === workers) { | 
|  | 48 | +      bench.start(); | 
|  | 49 | +      broadcast(); | 
|  | 50 | +    } | 
|  | 51 | +  } | 
|  | 52 | + | 
|  | 53 | +  function broadcast() { | 
|  | 54 | +    if (broadcasts++ === n) { | 
|  | 55 | +      bench.end(n); | 
|  | 56 | +      for (const worker of workerObjs) { | 
|  | 57 | +        worker.unref(); | 
|  | 58 | +      } | 
|  | 59 | +      return; | 
|  | 60 | +    } | 
|  | 61 | +    for (const worker of workerObjs) { | 
|  | 62 | +      for (var i = 0; i < sends; ++i) | 
|  | 63 | +        worker.postMessage(payload); | 
|  | 64 | +    } | 
|  | 65 | +  } | 
|  | 66 | + | 
|  | 67 | +  function onMessage() { | 
|  | 68 | +    if (++msgCount === expectedPerBroadcast) { | 
|  | 69 | +      msgCount = 0; | 
|  | 70 | +      broadcast(); | 
|  | 71 | +    } | 
|  | 72 | +  } | 
|  | 73 | +} | 
0 commit comments