等待用户 IO 的 C++ 线程 ('getchar()') 在主进程中挂起'Py_Initialize()'

c++ thread waiting for user IO ('getchar()') hangs 'Py_Initialize()' in main process

本文关键字:进程 挂起 Py Initialize IO C++ 用户 等待 getchar 线程      更新时间:2023-10-16

我偶然发现了一个非常奇怪的问题。在我的代码中,我启动了一个线程来等待用户输入——以防用户想要中断主进程。在这个线程运行之后,我尝试用python做一些计算。线程使用getchar()查找用户输入——如果输入是返回,则设置一个布尔标志以使主进程停止正在做的事情。主进程每隔一段时间检查一次这个标志,如果设置了,就采取相应的操作。

示意图:

bool volatile stopper = false;
thread stopThread(interrupt, &stopper);
while( !stopper ) {
    /* ... stuff ... */
    Py_Initialize();                            // this doesn't return unless 'interrupt()' completes.
    /* ... do things with python object ... */
} 

中断方法是这样的,

void interrupt(bool *st) {
    char ch;   
    while( ch != 'n' ) {
        ch = getchar();
    }
    *st = true;
}

如果我用sleep(10)替换getchar() while-loop, Py_Initialize()返回良好,一切都很好。为什么IO请求阻塞了Py_Initialize() ?

谢谢!

当您调用像getchar这样的I/O函数时,您在某个I/O对象上持有一个锁,直到该函数终止。在多线程程序中无限期地持有锁是非常糟糕的形式,因为这将导致任何试图获取该锁的线程无限期地阻塞。不要在多线程程序中调用阻塞I/O函数