Converting the last example, that uses Python from multiple threads, is actually quite easy. All the hard work has already been done!
static void
doWorkerThread( int threadNo )
{
Interpreter interp ;
for ( int i=0 ; i < 5 ; ++i )
{
BEGIN_PYTHON_INTERPRETER( interp )
{
// execute some Python
stringstream buf ;
buf << "print \"Thread " << threadNo << ": pass " << 1+i << "\"" ;
Interpreter::runSimpleString( buf.str().c_str() ) ;
}
END_PYTHON_INTERPRETER()
// sleep for a short time
Sleep( rand() % 100 ) ;
}
}
We create an Interpreter object for each thread, and use an InterpreterLock object (managed by the BEGIN/END_PYTHON_INTERPRETER macros) to take care of swapping it in and out when we want to use it.
The only thing to be careful about here is that because we're in a worker thread, any exceptions that get thrown won't get caught by the main thread's catch handler; each worker thread needs its own try/catch block.
Download the source code here.Have your say










I am a 
