Embed python interpreter in multi-threaded c++ application
yslee
yslee at vmstech.po.my
Wed Sep 20 08:10:48 EDT 2000
This is my Python script (test.py) :
=====================================
test.py
=====================================
import time, sys
name=sys.argv[0]
id=sys.argv[1]
i=0
delay=int(id)
while i<10:
print name, id, i
i=i+1
time.sleep(delay)
=====================================
end of test.py
=====================================
In the following simple C++ test program (test.cpp), I'm creating 3 threads
each will run the above script.
=====================================================
test.cpp
=====================================================
#include "stdafx.h"
#include "python.h"
DWORD WINAPI MyThreadProc(LPVOID lpParameter)
{
if (Py_NewInterpreter()==NULL)
printf("Fails to create new sub interpreter (%d)\n", (int)lpParameter);
FILE* fp;
char *argv[2];
argv[0]="d:\\projects\\python\\test\\test.py";
char temp[256];
sprintf(temp, "%d", (int)lpParameter);
argv[1]=temp;
PySys_SetArgv(2, argv);
if( (fp = fopen( "test.py", "r" )) == NULL )
printf( "The file 'test.py' was not opened (%d)\n", (int)lpParameter);
else
printf( "The file 'test.py' was opened (%d)\n", (int)lpParameter);
if (PyRun_SimpleFile(fp, "d:\\projects\\python\\test\\test.py")!=0)
printf("PyRun_SimpleFile fails (%d)\n", (int)lpParameter);
printf("thread (%d) exiting\n", (int)lpParameter);
return(0);
}
int main(int argc, char* argv[])
{
Py_Initialize();
PyEval_InitThreads();
printf("Hello World!\n");
DWORD id;
for (int i=1;i<4;i++)
CreateThread(NULL, 0, MyThreadProc, (LPVOID)i, 0, &id);
getch();
Py_Finalize();
return 0;
}
======================================================
end of test.cpp
======================================================
The script in thread 1 will print 1 to 10 at an interval of 1 second, 2
second for thread 2, 3 second for thread 3. Therefore script in thread 1
will end first (i.e. after 10 seconds). My problem is : right after thread
1 exits, the script in thread 2 and 3 will stop executing in the middle.
What have I done wrong?
YS Lee
C/C++ Software Developer
More information about the Python-list
mailing list