C++线程中嵌python

摘自:http://blog.niwota.com/rss/woblog
C++线程中嵌入python,线程并不是安全的,需要锁机制保证线程安全,我试了2种锁机制,一种是C++线程Mutex锁,另一种是python本身的线程锁
1、C++线程Mutex锁:
加锁的Code
#ifdef WIN32
EnterCriticalSection((CRITICAL_SECTION *)_mutex);
#else
pthread_mutex_lock(&_mutex);
#endif
解锁的Code
#ifdef WIN32
LeaveCriticalSection((CRITICAL_SECTION *)_mutex);
#else
pthread_mutex_unlock(&_mutex);
#endif
2、python本身的线程锁机制
    PyEval_InitThreads();
    mainThreadState = PyThreadState_Get();
    mainInterpreterState = mainThreadState->interp;
    myThreadState = PyThreadState_New(mainInterpreterState);
    PyEval_ReleaseLock();
    PyEval_AcquireLock();
    tempState = PyThreadState_Swap(myThreadState);
   
    //TODO:在这儿加入调用Python函数的代码   
    PyThreadState_Swap(tempState);
    PyEval_ReleaseLock();
    PyThreadState_Clear(myThreadState);
    PyThreadState_Delete(myThreadState);
3、对上面2种线程锁机制多次测试结果:
3.1 先把锁机制代码注销,多次测试后,程序崩溃,调试core文件,崩溃原因跟python有关
3.2 使用Mutex锁,多次测试,程序稳定,未出现崩溃
3.3 使用Python本身的线程锁机制,程序稳定,未出现崩溃
另多次实验,发现相同的测试程序在linux上运行速度比Windows快不少。