Make embedded CPython not touch stdio on init

31 Views Asked by At

The scheme of my application is as follows:

  1. at the very beginning I set the stdio streams to the binary mode (on Windows)
  2. next I start a separate thread which reads data from stdin which are supposed to be application-specific commands from the parent process:
void messageReceiverMain()
{
    auto& inStream = std::cin;
    while (true)
    {
        static const int BUFFER_SIZE = 3;
        char buffer[BUFFER_SIZE];
        inStream.read(buffer, BUFFER_SIZE);
        if (std::memcmp(buffer, "cmd", BUFFER_SIZE) == 0)
        {
            // perform some action
        }
    }
}
  1. after that, in the main thread, I init the CPython embedded interpreter using the isolated config:
PyStatus status;
PyConfig config;
PyConfig_InitIsolatedConfig(&config);

status = Py_InitializeFromConfig(&config);

What I see is that the application hangs on the Py_InitializeFromConfig function. If I comment out the second step (running the thread), then the hang is not present.

If I change the order of step 2 and 3, the hang is not present (though I need to use a hack to change the order so such a solution is not very convenient).

It looks like CPython is performing some kind of initialisation of stdio which results in a hang as long as another thread is reading stdin.

Is it possible to make CPython not touch stdio at all so the hang is not present?

In the embedded interpreter I only execute a code which does not use stdio at all.

0

There are 0 best solutions below