如何在工作线程中使用闭合句柄

2024-10-02 22:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows中使用线程将c++编写的插件连接到python脚本。线程将在会话期间被多次调用

问题:

如果我在_beginthread中传递ArgList,则在0x1E114A68(python27.dll)处发生错误“未处理的异常xxx.exe文件:0xc000005:读取位置0xFFFFFFFE时发生访问冲突。“,我想这是因为我在Windows开发人员中心的CreatingThreads中读取的:

“请注意,如果要在工作线程终止之前关闭它的句柄,则不会终止该工作线程。但是,句柄将不可用于后续函数调用。“

关于这个错误的起源,我说得对吗?我该如何度过这个难关?在

代码:

我用NULL作为ArgList调用{},并在工作线程中定义了{},只是为了让线程工作。以下是工作线程的代码:

注意:我在调试时注意到没有到达_endthread()。这正常吗?在

void py_embed (void*data){

char *argv[4]={"PythonPlugIn2","bridge","test_callsign","MAH543"};
int argc=4;

ofstream textfile3;
textfile3.open("FP_python_embed.txt");

PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue;
PyThreadState *mainThreadState,*myThreadState,*tempState;
PyInterpreterState *mainInterpreterState;

//To inform the interpreter about paths to Python run-time libraries
Py_SetProgramName(argv[0]);

// Initialize the Python Interpreter
Py_Initialize();

// Initialize thread support
PyEval_InitThreads();

// Save a pointer to the main PyThreadState object
mainThreadState = PyThreadState_Get();

// Get a reference to the PyInterpreterState
mainInterpreterState = mainThreadState->interp;

// Create a thread state object for this thread
myThreadState = PyThreadState_New(mainInterpreterState);

// Release global lock
PyEval_ReleaseLock();

// Acquire global lock
PyEval_AcquireLock();

// Swap in my thread state
tempState = PyThreadState_Swap(myThreadState);

// Build the name object
pName = PyString_FromString(argv[1]);

// Load the module object
pModule = PyImport_Import(pName);

// pDict is a borrowed reference 
pDict = PyModule_GetDict(pModule);

// pFunc is also a borrowed reference 
pFunc = PyDict_GetItemString(pDict, argv[2]);

//Do the Python things
PyObject *pArgs2, *pValue2;
pArgs2=Py_BuildValue("(s)",argv[3]);
pValue2 = PyObject_CallObject(pFunc, pArgs2);
textfile3<<PyInt_AsLong(pValue2)<<endl<<" worked1";
textfile3.close();

// Clean up
Py_DECREF(pModule);
Py_DECREF(pName);

// Swap out the current thread
PyThreadState_Swap(tempState);

// Release global lock
PyEval_ReleaseLock();

// Clean up thread state
PyThreadState_Clear(myThreadState);
PyThreadState_Delete(myThreadState);

// Finish the Python Interpreter
Py_Finalize();

_endthread();
};

我从主线程(在工作线程完成之前关闭)调用它的方法:

^{2}$

注:问题1与此相关的是here


Tags: thepyobject线程threadswapargvpdict
1条回答
网友
1楼 · 发布于 2024-10-02 22:23:34

所以,我终于找到了问题所在。希望这能帮助那些有同样问题的人

我仍然不完全理解这是如何工作的,但我基本上需要使用c++中的new(以及c中的malloc)在堆上动态分配内存。有关此here的详细信息

在我的情况下,我需要这样做:

#define NUM_ARGUMENTS 4
typedef struct{
int argc;
char *argv[NUM_ARGUMENTS];
}SENDTOPY;

然后在主线上:

^{pr2}$

我仍然需要更好地理解这一点,还需要学习如何在结尾使用delete取消分配,但我的方法是正确的。在

注意:我仍然需要与此相关的Question1帮助,所以请看一下。在

相关问题 更多 >