Python论坛  - 讨论区

标题:[python-chinese] 关于多线程下python解释器的问题

2006年04月18日 星期二 18:58

吴俊玉 wujunyu at gmail.com
Tue Apr 18 18:58:10 HKT 2006

以下有两段程序都是多线程环境下的python解释器,
但是

#include 

#include 



PyThreadState * mainThreadState;



unsigned long WINAPI run(void * arg)

{

     PyEval_AcquireLock();

     PyInterpreterState * mainInterpreter = mainThreadState->interp;

     PyThreadState * threadInfo = PyThreadState_New(mainInterpreter);

     PyObject_CallMethod((PyObject *)arg, "start", NULL);

     PyEval_ReleaseLock();

     return 0;

}



int main(int argc,char ** argv)

{

     Py_Initialize();

     PyEval_InitThreads();

     PyObject *TankModule = NULL;

     PyObject *TankDict = NULL;

     PyObject *TankClassObj = NULL;

     PyObject *TankObject = NULL;

     PyObject *ConstructArgs=NULL;

     mainThreadState = PyThreadState_Get();



     TankModule = PyImport_ImportModule("Tank");

     TankDict = PyModule_GetDict(TankModule);

     TankClassObj = PyDict_GetItemString(TankDict,"Tank");

     ConstructArgs=Py_BuildValue("iiiii",10,10,10,10,100);

     TankObject = PyObject_Call(TankClassObj, ConstructArgs, NULL);



     HANDLE tmpthread=CreateThread(NULL,0,run,TankObject,0,NULL);

     WaitForSingleObject(tmpthread,INFINITE);

     Py_Finalize();

     return 0;
}
可以执行!
我把TankObject封装到类当中就不能执行了,
更奇怪的是居然TankObject为NULL
代码如下:

#include 
#include 

PyThreadState * mainThreadState;

class T
{
public:
 T(PyObject *t):ref(t){Py_INCREF(t);}
 void go(){PyObject_CallMethod((PyObject *)ref, "start", NULL);}
private:
 PyObject * ref;
};

unsigned long WINAPI run(void * arg)
{
 PyEval_AcquireLock();
 PyInterpreterState * mainInterpreter = mainThreadState->interp;
 PyThreadState * threadInfo = PyThreadState_New(mainInterpreter);
 ((T*)arg)->go();
 PyEval_ReleaseLock();
 return 0;
}

int main(int argc,char ** argv)
{
 Py_Initialize();
 PyEval_InitThreads();
 PyObject *TankModule = NULL;
 PyObject *TankDict = NULL;
 PyObject *TankClassObj = NULL;
 PyObject *TankObject = NULL;
 PyObject *ConstructArgs=NULL;
 mainThreadState = PyThreadState_Get();

 TankModule = PyImport_ImportModule("Tank");
 TankDict = PyModule_GetDict(TankModule);
 TankClassObj = PyDict_GetItemString(TankDict,"Tank");
 ConstructArgs=Py_BuildValue("iiiii",10,10,10,10,100);
 TankObject = PyObject_Call(TankClassObj, ConstructArgs, NULL);

 HANDLE tmpthread=CreateThread(NULL,0,run,new T(TankObject),0,NULL);
 WaitForSingleObject(tmpthread,INFINITE);
 Py_Finalize();
 return 0;
}
两段程序主干一样!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.exoweb.net/pipermail/python-chinese/attachments/20060418/096bea4f/attachment.html

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号