|
| 1 | +import Decimal from "decimal.js"; |
| 2 | +import { myworker } from "./decimal-myworker"; |
| 3 | + |
| 4 | +export async function decimalCalculatePi( |
| 5 | + createworker, |
| 6 | + piwei, |
| 7 | + threadgeshu |
| 8 | +) { |
| 9 | + var p, |
| 10 | + x = 0; |
| 11 | + p = new Decimal(0); |
| 12 | + |
| 13 | + Decimal.set({ precision: piwei }); |
| 14 | + // myworker.length = threadgeshu; |
| 15 | + // myworker.fill(undefined); |
| 16 | + // finishflag = []; |
| 17 | + // finishflag.length = threadgeshu; |
| 18 | + /* var worker1; |
| 19 | +if (typeof worker1 == "undefined") { |
| 20 | +worker1 = new Worker("mythread1.js"); |
| 21 | +} |
| 22 | +
|
| 23 | +for (var i = 0, len = threadgeshu; i < len; i++) { |
| 24 | +myworker[i] = worker1; |
| 25 | +} |
| 26 | +*/ |
| 27 | + for (var i = 0, len = threadgeshu; i < len; i++) { |
| 28 | + if (myworker.length >= threadgeshu) { |
| 29 | + break; |
| 30 | + } else { |
| 31 | + myworker.push(createworker()); |
| 32 | + } |
| 33 | + } |
| 34 | + console.log(myworker); |
| 35 | + await Promise.all( |
| 36 | + myworker.map(function (currentValue, index, arr) { |
| 37 | + // arr[index] = undefined; |
| 38 | + // arr[index] = arr[index] || new Worker("mythread1.js"); |
| 39 | + console.log(myworker); |
| 40 | + return new Promise((res, rej) => { |
| 41 | + currentValue.onmessage = function (event) { |
| 42 | + console.log( |
| 43 | + "主线程从副线程" + (index + 1) + "接收" + "event.data\n" |
| 44 | + ); |
| 45 | + console.log( |
| 46 | + "第一个参数", |
| 47 | + event.data[0], |
| 48 | + "\n第二个参数", |
| 49 | + event.data[1] |
| 50 | + ); |
| 51 | + // console.log(...event.data); |
| 52 | + var p1 = new Decimal(event.data[0]); |
| 53 | + p = Decimal.add(p, p1); |
| 54 | + x = Math.max(x, parseInt(event.data[1])); |
| 55 | + // finishflag[index] = 1; |
| 56 | + // threadfinish(); |
| 57 | + res(); |
| 58 | + }; |
| 59 | + currentValue.onerror = (e) => { |
| 60 | + console.error("Error:", e.error, e.message); |
| 61 | + // for (var key in e) { |
| 62 | + // console.error(key, e[key]) |
| 63 | + // } |
| 64 | + // console.error(e) |
| 65 | + currentValue.terminate(); |
| 66 | + // arr[index] = void 0; |
| 67 | + rej(new Error(e.error + e.message)); |
| 68 | + // throw e; |
| 69 | + }; |
| 70 | + currentValue.postMessage([piwei, threadgeshu, index]); |
| 71 | + }); |
| 72 | + }) |
| 73 | + ); |
| 74 | + let resultpi = p.toString(); |
| 75 | + return [resultpi, x]; |
| 76 | +} |
0 commit comments