且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python C API - 停止执行(并在以后继续执行)

更新时间:2022-04-23 06:09:50

如果我理解你的问题,你有一个C ++程序,蟒蛇。当Python完成执行一个函数时,你想暂停解释器,并选择C ++代码停止在哪里。有一段时间以后,你的C ++程序需要回到python,并让python解释器从中断。

If I understand your problem, you have a C++ program that calls into python. When python finishes executing a function, you want to pause the interpreter and pick up where the C++ code left off. Some time later your C++ program needs to cal back into python, and have the python interpreter pick up where it left off.

我不认为你可以这样做容易与一个螺纹。在暂停解释器之前,堆栈看起来像这样:

I don't think you can do this very easily with one thread. Before you pause the interpreter the stack looks like this:

[ top of stack ]
[ some interpreter frames ]
[ some c++ frames ] 

要暂停解释器,需要保存解释器框架,并跳回到最顶层的C ++框架。然后要取消暂停,你需要恢复解释器框架,并将堆栈跳到你离开的地方。跳跃是可行的(请参阅 http://en.wikipedia.org/wiki/Setjmp.h),但是保存和恢复堆栈更加困难。我不知道有一个API这样做。

To pause the interpreter, you need to save off the interpreter frames, and jump back to the top-most C++ frame. Then to unpause, you need to restore the interpreter frames, and jump up the stack to where you left off. Jumping is doable (see http://en.wikipedia.org/wiki/Setjmp.h), but saving and restoring the stack is harder. I don't know of an API to do this.

但是你可以用两个线程做到这一点。在c ++程序开始时创建的线程(称为线程1)运行c ++代码,并创建线程2来运行python解释器。

However you could do this with two threads. The thread created at the start of your c++ program (call it thread 1) runs the c++ code, and it creates thread 2 to run the python interpreter.

正在运行c ++代码),线程1正在执行,线程2被阻止(例如条件变量,请参阅 https ://computing.llnl.gov/tutorials/pthreads/ )。当运行或取消暂停解释器线程1时,会发出条件变量的信号,并等待它。这唤醒线程2(运行解释器)并使线程1阻塞。当解释器需要暂停时,线程2通知条件变量并等待它(因此线程2块,线程1唤醒)。你可以在线程之间来回跳转到你的心脏的内容。希望这有助于。

Initially (when were running c++ code), thread 1 is executing and thread 2 is blocked (say on a condition variable, see https://computing.llnl.gov/tutorials/pthreads/). When you run or unpause the interpreter thread 1 signals the condition variable, and waits on it. This wakes up thread 2 (which runs the interpreter) and causes thread 1 to block. When the interpreter needs to pause, thread 2 signals the condition variable and waits on it (so thread 2 blocks, thread 1 wakes up). You can bounce back and forth between the threads to your heart's content. Hope this helps.