Created
November 27, 2018 06:33
-
-
Save Ethan-Arrowood/90d4c33adcbb678b26b46fb97a97af15 to your computer and use it in GitHub Desktop.
This code caused a segmentation fault in a one-off occurance. Fixed by fixing the TypeError that is thrown first by line 33 of script.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { | |
Worker, isMainThread, parentPort, workerData, threadId, MessageChannel | |
} = require('worker_threads') | |
//getting array from workerData | |
const array = workerData | |
// sort array | |
let sortedArray = array.sort((a, b) => a - b) | |
let thr = { | |
threadId, | |
sortedArray | |
} | |
//send back to parent using parentPort.postmessage | |
parentPort.postMessage(thr) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const assert = require('assert') | |
const { EventEmitter } = require('events') | |
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads') | |
const MAX_THREAD_COUNT = 8 | |
const nThreads = parseInt(process.argv[2]) | |
assert(nThreads <= MAX_THREAD_COUNT, `Number of threads cannot exceed ${MAX_THREAD_COUNT}`) | |
const data_fileName = process.argv[3] | |
const DATA = [ | |
7, 12, 19, 3, 18, 16, 4, 2, | |
6, 9, 18, 38, 15, 8, 123, 72, | |
4, 3, 11, 33, 15, 48, 13, 17, | |
23, 19, 30, 45, 31, 1, 14, 50 | |
] | |
// split up data in nThreads equal parts | |
const data_split = [] | |
const s = DATA.length / nThreads // size of sub array | |
for (let i = 0; i < DATA.length; i+=s) | |
data_split.push(DATA.slice(i, i+s)) | |
// event listener | |
const sortEmitter = new EventEmitter() | |
sortEmitter.on('sorted', ({ threadId, sortedArray }) => { | |
console.log(`threadId: ${threadId} | -> sortedArray: ${sortedArray}`) | |
}) | |
// send data to qsort threads | |
data_split.forEach(subArray => { | |
let qsortThread = new Worker('./qsort.js', { workerData: subArray }) | |
qsortThread.on('message', res => sortEmitter('sorted', res)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment