等待用户 IO 的 C++ 线程 ('getchar()') 在主进程中挂起'Py_Initialize()'
c++ thread waiting for user IO ('getchar()') hangs 'Py_Initialize()' in main process
我偶然发现了一个非常奇怪的问题。在我的代码中,我启动了一个线程来等待用户输入——以防用户想要中断主进程。在这个线程运行之后,我尝试用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函数
相关文章:
- 从不同进程中的另一个线程挂起/恢复线程或进程
- 从stdin读取时子进程挂起(fork/dup2竞争条件)
- 带有 QSharedMemory 的 IPC,如果其中一个进程挂起,则存在风险
- 在两个子进程之间管道时,C++ 进程挂起
- 启动子进程时的争用条件导致从管道读取挂起
- 其他进程在MPI_Sendrecv后挂起
- 无法从挂起进程的独立线程中的管道中读取
- 启动特定子进程后挂起进程
- 从 Python 子进程中的 stdin 读取挂起在 C++/Python IPC 中
- MPI 从进程在不再工作时挂起
- Linux:fork & execv,等待子进程挂起
- 如何防止长进程挂起wxwidgets窗口
- 将函数从挂起的dll复制到进程内存中
- 查找位置(寻找c++初学者)以创建Windows Vista x64 Ultimate的挂起进程程序
- 从c#调用x64 c++ DLL,进程挂起(更新)
- 我可以挂起除一个线程外的进程吗?
- 进程挂起,PIPE阻塞
- 确定进程是否挂起
- 如何在c++中挂起和恢复进程和线程
- 等待用户 IO 的 C++ 线程 ('getchar()') 在主进程中挂起'Py_Initialize()'