deasync icon indicating copy to clipboard operation
deasync copied to clipboard

Dead lock in some condition when use with MessagePort

Open mmis1000 opened this issue 5 years ago • 1 comments

The message port never fires the port2.onmessage after the deasync'ed method was called.

Minimal reproduction

const deasync = require('deasync')

const {
    Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

if (isMainThread) {
    const { port1, port2 } = new MessageChannel()

    port1.onmessage = () => {
        console.log('main get')
        port1.postMessage('go')
    }

    const worker = new Worker(__filename, {
        workerData: { port2 },
        transferList: [port2]
    });

    worker.on('message', () => {
        worker.postMessage('Hello World')
    });

    worker.on('exit', (code) => {
        console.log(`Worker stopped with exit code ${code}`);
    });

} else {
    const port2 = workerData.port2;

    let cb = null

    port2.onmessage = (ev) => {
        // this will never be called if the deasync'ed method was called inside ` parentPort.once('message',`
        console.log('worker 2 end')
        cb(null, 'data: ' + ev.data)
    }

    const asyncMethod = (cb_) => {
        cb = cb_
        port2.postMessage('')
    }

    const syncMethod = deasync(asyncMethod)

    parentPort.once('message', (message) => {
        console.log(message)

        // 1. this do not work
        console.log('done: ' + syncMethod())

        // 2. this does work
        // setImmediate(() => console.log('done: ' + syncMethod()))
            
        // 3. this does work
        // asyncMethod((err, res) => {
        //     console.log('done: ' + res)
        // })
    });

    // 4. this also work
    // console.log('done: ' + syncMethod())

    parentPort.postMessage('')
}

I am not really understand

  1. how this happened
  2. why this happened
  3. why it only happens when called inside the parentPort.once('message',
  4. who is responsible for this.

But since this did not happen without deasync I am going to open the issue here.

If I am wrong, just close this issue.

mmis1000 avatar Nov 25 '20 07:11 mmis1000

any workaround about this issue? got a simulator problem here

tango5614 avatar Dec 15 '20 03:12 tango5614