looking for some solutions? You are welcome.

SOLVED: Multiple calls to Python interpreter embedded in C++ application yield segmentation fault

Matthias Möller:

This question has been posted earlier as an issue at rigetti/pyquil, where it has been recommended to ask Python experts before considering it a bug in Rigetti's pyquil library:

Consider the following mini application that creates a string containing QASM code in the host application and invokes the Python interpreter:

#include <Python.h>
#include <sstream>

static void run()
{
  std::stringstream ss;

  ss << "import pyquil\n"
     << "qasm = 'H 0'\n"
     << "p = pyquil.Program(qasm)\n"
     << "qc = pyquil.get_qc('9q-square-qvm')\n"
     << "result = qc.run_and_measure(p, trials=1024)\n"
     << "print(result)\n";

  Py_Initialize();
  PyRun_SimpleString(ss.str().c_str());
  Py_Finalize();
}

int main()
{
  run();
  run();
  return 0;
}

Remark: In my real program am not using PyRun_SimpleString but, instead, the approach described here to extract the return value. The problem is the same, so the above program is just meant as illustrating example to keep things as simple as possible.

Compiling the code under macOS 10.13.6 as follows

g++ -I/usr/local//homebrew/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/include/python3.7m -L/usr/local//homebrew/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib -lpython3.7m demo.cxx -o demo.exe

yields the following error:

{0: array([1, 1, 0, ..., 1, 0, 0]), 1: array([0, 0, 0, ..., 0, 0, 0]), 2: array([0, 0, 0, ..., 0, 0, 0]), 3: array([0, 0, 0, ..., 0, 0, 0]), 4: array([0, 0, 0, ..., 0, 0, 0]), 5: array([0, 0, 0, ..., 0, 0, 0]), 6: array([0, 0, 0, ..., 0, 0, 0]), 7: array([0, 0, 0, ..., 0, 0, 0]), 8: array([0, 0, 0, ..., 0, 0, 0])}
Segmentation fault: 11

Removing the second run() from the main() function, i.e. no second invocation of the Python interpreter, solves the problem.

The segmentation fault occurs already at the import pyquil line. That is, already this code produces a segmentation fault in the second call to run():

#include <Python.h>
#include <sstream>

static void run()
{
  std::stringstream ss;

  ss << "import pyquil\n";

  Py_Initialize();
  PyRun_SimpleString(ss.str().c_str());
  Py_Finalize();
}

int main()
{
  run();
  run();
  return 0;
}

I have been using multiple invocations of the Python interpreter from the same host application with many other Python modules and never encountered this problem. Any help is appreciated.



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent