से पायथन कोड को कॉल करना मैं बहुत उलझन में हूं कि मैं सी (या सी ++) थ्रेड से पायथन कोड को कॉल करते समय थ्रेड-सुरक्षा को कैसे सुनिश्चित कर सकता हूं। इस stackoverflow answer के रूप में ज्यादा पुष्टि करने के लिए लगता है,सी थ्रेड
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
/* Perform Python actions here. */
result = CallSomeFunction();
/* evaluate result or handle exception */
/* Release the thread. No Python API allowed beyond this point. */
PyGILState_Release(gstate);
और वास्तव में:
Python documentation कह जा सकता है कि ऐसा करने के लिए हमेशा की तरह मुहावरा है लगता है। लेकिन एक टिप्पणीकार (एक बहुत ही उच्च प्रतिष्ठा के साथ) अन्यथा कहते हैं। टिप्पणीकर्ता का कहना है कि आपको PyEval_RestoreThread()
/PyEval_SaveThread()
का उपयोग करना चाहिए।
डॉक्स इस बात की पुष्टि करने लगते हैं:
PyThreadState* PyEval_SaveThread()
Release the global interpreter lock (if it has been created and
thread support is enabled) and reset the thread state to NULL,
returning the previous thread state (which is not NULL). If the lock
has been created, the current thread must have acquired it. (This
function is available even when thread support is disabled at compile
time.)
void PyEval_RestoreThread(PyThreadState *tstate)
Acquire the global interpreter lock (if it has been created and thread
support is enabled) and set the thread state to tstate, which must not
be NULL. If the lock has been created, the current thread must not have
acquired it, otherwise deadlock ensues. (This function is available even
when thread support is disabled at compile time.)
रास्ता डॉक्स इस का वर्णन है, ऐसा लगता है कि PyEval_RestoreThread()
/PyEval_SaveThread()
मूल रूप से एक म्युटेक्स लॉक/अनलॉक मुहावरा है। तो यह समझ में आता है कि सी से किसी भी पायथन कोड को कॉल करने से पहले, आपको पहले जीआईएल को लॉक करने की आवश्यकता है, और उसके बाद इसे अनलॉक करें।
तो यह कौन सा है? जब सी से अजगर कोड बुला, मैं का उपयोग करना चाहिए:
PyGILState_Ensure()/PyGILState_Release()
या
PyEval_RestoreThread/PyEval_SaveThread
?
और वास्तव में क्या अंतर है?