My problem is resolved. You may have your problems more specific, so I'm trying to write my solution in a more general way. Hope this helps.
- In main stream C
- initialize the Python environment at the very beginning:
PyThreadState * mainThreadState = NULL; if(!Py_IsInitialized()) Py_Initialize(); mainThreadState = = PyThreadState_Get();
pthread_create(pthread_id, NULL, thread_entrance, NULL);
- In each thread, or we can say in the body of the thread_entrance function
PyEval_AcquireLock(); PyInterpreterState * mainInterpreterState = mainThreadState->interp; PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState); PyEval_ReleaseLock();
- enter the python code here:
PyEval_AcquireLock(); PyThreadState_Swap(myThreadState); PyEval_CallObject(py_function, py_arguments); PyThreadState_Swap(NULL); PyEval_ReleaseLock();
- return to main stream C
- when each thread finishes its work, python environment terminates
pthread_join(pthread_id, NULL); PyEval_RestoreThread(mainThreadState); Py_Finalize();
alwinlin
source share