C++ Embedded Phython and multithreading problem

Joined
May 25, 2010
Messages
2
Reaction score
0
Hello all C++/Pyhton gurus. I'm having a little big problem trying to create an application with embedded Python and C++. Here you have a function I want to be called multiple times at the same time. I'm trying to just have one interpreter but multiple threads calling a function from a script. The problem comes when calling PyObject_CallFunction() in a second or third thread crashes my application.

The reason I don't want to use multiple interpreters is I don't want to use more memory/cpu resources than what is needed.

I tried to use PyEval_InitThreads(), but it didn't help.

My questions are:

1)Can I call multiple times a phython function using only one interpreter, at the same time?

2)If so, how?

3)If not, what procedure should I take then?

Thanks.


PHP:
BounceResult * BounceC(PyObject *&pFunc, PyObject *& pArgs, PyObject *& pObject, PyObject *& pMsg)
{
	PyObject *pValue;
	BounceResult Object;
	
	pArgs = PyTuple_New(2);

	PyTuple_SetItem(pArgs, 0, pObject);
	PyTuple_SetItem(pArgs, 1, pMsg);
    

	if(pArgs && pMsg && pObject)
	{
		pValue = PyObject_CallFunction(pFunc, "O", pArgs);
	}
	else
	{
		return NULL;
	}
	
	if (!pValue) 
        {
        fprintf(stderr, "Cannot convert argument\n");
		return NULL;
    }            

    if (pValue != NULL) 
    {
        Py_DECREF(pValue);
    }
    else 
    {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
        return NULL;
    }
	return &Object;
}
 
Joined
May 25, 2010
Messages
2
Reaction score
0
A practical crashing example:

PHP:
#include "stdafx.h"
#include <windows.h>
#include <string>
#include <Python.h>

using namespace std;

int pp = 0;

DWORD WINAPI EmailChecker( LPVOID lpParam ) 
{
  PyRun_SimpleString("from time import time,ctime\n"
                     "print 'Today is',ctime(time())\n");
	
  printf("Finished thread nr: %i\n", pp++ );
	
	return 0;
}


int _tmain()
{
	const int nhandles = 100;

	HANDLE hThread[nhandles];
	DWORD dwThreadIdArray[nhandles];

	Py_Initialize();
	PyEval_InitThreads();

	printf("Game started...\n");

	for(int i = 0; i < nhandles; i++)
	{
		hThread[i] = CreateThread( 
			NULL,                   // default security attributes
			0,                      // use default stack size  
			EmailChecker,       // thread function name
			0,          // argument to thread function 
			0,                      // use default creation flags 
			&dwThreadIdArray[i]);   // returns the thread identifier 
	}	
	
	Sleep(9999999999999999);
	Py_Finalize();
	return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top