OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 the V8 project authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 $.agent = (function () { |
| 6 |
| 7 var workers = []; |
| 8 var i32a = null; |
| 9 var pendingReports = []; |
| 10 |
| 11 // Agents call Atomics.wait on this location to sleep. |
| 12 var SLEEP_LOC = 0; |
| 13 // 1 if the started worker is ready, 0 otherwise. |
| 14 var START_LOC = 1; |
| 15 // The number of workers that have received the broadcast. |
| 16 var BROADCAST_LOC = 2; |
| 17 // Each worker has a count of outstanding reports; worker N uses memory |
| 18 // location [WORKER_REPORT_LOC + N]. |
| 19 var WORKER_REPORT_LOC = 3; |
| 20 |
| 21 function workerScript(script) { |
| 22 return ` |
| 23 var index; |
| 24 var i32a = null; |
| 25 var broadcasts = []; |
| 26 var pendingReceiver = null; |
| 27 |
| 28 function handleBroadcast() { |
| 29 if (pendingReceiver && broadcasts.length > 0) { |
| 30 pendingReceiver.apply(null, broadcasts.shift()); |
| 31 pendingReceiver = null; |
| 32 } |
| 33 }; |
| 34 |
| 35 var onmessage = function(msg) { |
| 36 switch (msg.kind) { |
| 37 case 'start': |
| 38 i32a = msg.i32a; |
| 39 index = msg.index; |
| 40 (0, eval)(\`${script}\`); |
| 41 break; |
| 42 |
| 43 case 'broadcast': |
| 44 Atomics.add(i32a, ${BROADCAST_LOC}, 1); |
| 45 broadcasts.push([msg.sab, msg.id]); |
| 46 handleBroadcast(); |
| 47 break; |
| 48 } |
| 49 }; |
| 50 |
| 51 var $ = { |
| 52 agent: { |
| 53 receiveBroadcast(receiver) { |
| 54 pendingReceiver = receiver; |
| 55 handleBroadcast(); |
| 56 }, |
| 57 |
| 58 report(msg) { |
| 59 postMessage(msg); |
| 60 Atomics.add(i32a, ${WORKER_REPORT_LOC} + index, 1); |
| 61 }, |
| 62 |
| 63 sleep(s) { Atomics.wait(i32a, ${SLEEP_LOC}, 0, s); }, |
| 64 |
| 65 leaving() {} |
| 66 } |
| 67 };`; |
| 68 } |
| 69 |
| 70 var agent = { |
| 71 start(script) { |
| 72 if (i32a === null) { |
| 73 i32a = new Int32Array(new SharedArrayBuffer(256)); |
| 74 } |
| 75 var w = new Worker(workerScript(script)); |
| 76 w.index = workers.length; |
| 77 w.postMessage({kind: 'start', i32a: i32a, index: w.index}); |
| 78 workers.push(w); |
| 79 }, |
| 80 |
| 81 broadcast(sab, id) { |
| 82 Atomics.store(i32a, BROADCAST_LOC, 0); |
| 83 |
| 84 for (var w of workers) { |
| 85 w.postMessage({kind: 'broadcast', sab: sab, id: id|0}); |
| 86 } |
| 87 |
| 88 while (Atomics.load(i32a, BROADCAST_LOC) != workers.length) {} |
| 89 }, |
| 90 |
| 91 getReport() { |
| 92 for (var w of workers) { |
| 93 while (Atomics.load(i32a, WORKER_REPORT_LOC + w.index) > 0) { |
| 94 pendingReports.push(w.getMessage()); |
| 95 Atomics.sub(i32a, WORKER_REPORT_LOC + w.index, 1); |
| 96 } |
| 97 } |
| 98 |
| 99 return pendingReports.shift() || null; |
| 100 }, |
| 101 |
| 102 sleep(s) { Atomics.wait(i32a, SLEEP_LOC, 0, s); } |
| 103 }; |
| 104 return agent; |
| 105 |
| 106 })(); |
OLD | NEW |