fridgerator / PyNode

Node - Python Interop
154 stars 14 forks source link

Solving segmentation fault when calling `startInterpreter` multiple times #36

Open milliele opened 2 years ago

milliele commented 2 years ago

Heya I think PyNode is almost the best to do python-JS Interop in a light-weighted, fast way!!!

However, one problem I encountered was that there would be a segmentation fault raised if we failed to ensure that pynode.startInterpreter() was called only once. I believe that this is because the GIL is released when calling pynode.startInterpreter() again and PyUnicode_DecodeFSDefault("pynode"); in the function requires GIL.

In most cases, PyNode works very well because I put the initialized pynode (with interpreter started and syspath added) in a module, like:

// in util.js
function loadPyNode() {
  const pynode = require('@fridgerator/pynode');
  pynode.startInterpreter();
  return pynode;
}

module.exports = {
  pynode
}

// in A.test.js
const { pynode } = require('./utils');
// test suite 1

// in B.test.js
const { pynode } = require('./utils');
// test suite 2

However, when I was doing unit tests by jest and there were multiple test files, utils.js was called for each test file, even if the test files were actually executed in the same subprocess, which led to duplicated calling of startInterpreter and thus segmentation fault.

milliele commented 2 years ago

I've opened a PR (#37 ) trying to fix this, and it works for my project on both Mac OS and Ubuntu 18.04 using python 3.8 & Node 16. Hope this could make pynode more robust.