Advertisement
Guest User

Untitled

a guest
Mar 2nd, 2012
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. int main(int argc, char *argv[])
  2. {
  3.     Py_Initialize();
  4.     PyEval_InitThreads();
  5.     PyThreadState*  mainThreadState = PyThreadState_Get();
  6.     PyInterpreterState * mainInterpreterState = mainThreadState->interp;
  7.     PyEval_ReleaseLock();
  8.  
  9.     QList<TPyScriptRunnable*> scripts;
  10.     for( int i = 0; i < 2; ++i ){
  11.         PyEval_AcquireLock();
  12.         PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState);
  13.         PyEval_ReleaseLock();
  14.  
  15.         scripts.push_back( new TPyScriptRunnable( QString("MM%1").arg(i), myThreadState ) );
  16.     }
  17.    
  18. //  QThreadPool::globalInstance()->setMaxThreadCount( 1 );
  19.     foreach( TPyScriptRunnable *script, scripts )
  20.         QThreadPool::globalInstance()->start(script);
  21.  
  22.     QCoreApplication a(argc, argv);
  23.     QTimer::singleShot( 5000, &a, SLOT(quit()) );
  24.     a.exec();
  25.  
  26.     PyEval_RestoreThread(mainThreadState);
  27.     Py_Finalize();
  28.     return 0;
  29. }
  30.  
  31.  
  32. class TPyScriptRunnable : public QRunnable
  33. {
  34. public:
  35.     TPyScriptRunnable( const QString &arg, PyThreadState *threadState )
  36.     : m_arg(arg), m_threadState(threadState) {}
  37.     virtual ~TPyScriptRunnable()
  38.     {
  39.         PyEval_AcquireLock();
  40.         PyThreadState_Swap(NULL);
  41.         PyThreadState_Clear(m_threadState);
  42.         PyThreadState_Delete(m_threadState);
  43.         PyEval_ReleaseLock();
  44.     }
  45.     //
  46.     virtual void run()
  47.     {
  48.         PyEval_AcquireLock();
  49.         PyThreadState_Swap(m_threadState);
  50.  
  51.         QString str =   QString("import time\n"
  52.                     "somefilename = open('d:\\py_test\\%1','w')\n"
  53.                     "print somefilename.fileno()\n"
  54.                     "somefilename.write('111')\n"
  55.                     "print somefilename.fileno()\n"
  56.                     "time.sleep(1)\n"
  57.                     "somefilename.write('222')\n"
  58.                     "print somefilename.fileno()\n").arg(m_arg);
  59.         PyRun_SimpleString( str.toAscii().constData() );
  60.  
  61.         PyThreadState_Swap(NULL);
  62.         PyEval_ReleaseLock();
  63.     }
  64. private:
  65.     QString m_arg;
  66.     PyThreadState   *m_threadState;
  67. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement