Latest Blogs

Killing a Python Sub-interpreter That Uses Threads

I was having a tough time figuring out a solution to ending sub-interpreters in Viper when that sub-interpreter had multiple threads. Just recently, though, I found a solution that works for me:

// The current tstate must be the original tstate when we call PyEval_ThreadsInitialized
PyThreadState_Swap(m_pThreadState);

/* If the plug-in has enabled threads (by using any sort of threading),
* we must kill the threads before destroying the interpreter */
if (PyEval_ThreadsInitialized())
{
// Loop through all threads in the current interpreter and raise SystemExit
PyThreadState *curstate = m_pInterpState->tstate_head;
while (curstate != NULL && curstate->interp == m_pInterpState)
{
PyThreadState_Swap(curstate);

PyThreadState_SetAsyncExc(curstate->thread_id, _PyExc_SystemExit);
curstate = curstate->next;

PyThreadState_Swap(NULL);
}

/* This is very much frowned upon in Py_EndInterpreter, but this little
* hack makes Python happy. I don't know the consequences of this line,
* but until I do, I won't feel guilty >_> */
m_pInterpState->tstate_head = m_pThreadState;
}

PyThreadState_Swap(m_pThreadState);
Py_EndInterpreter(m_pThreadState);

m_pInterpState is the PyInterpreterState of the sub-interpreter it's destroying, and m_pThreadState is the original PyThreadState returned by Py_NewInterpreter. I think you can tell by my comments that you should take caution when using this code. However, the code works perfectly: the threads die and the interpreter gets killed, all without a single runtime error.

Comments

Re: Killing a Python Sub-interpreter That Uses Threads

WAKE UP SHAWTY

Re: Killing a Python Sub-interpreter That Uses Threads

When students are stuck with essay papers accomplishing, therefore I will recommend to buy essays online at some classification essay service in such situation.