在python扩展中创建可连接线程的最安全方法
我正在开发一个python扩展,它使用在python扩展中创建可连接线程的最安全方法,python,c++,pthreads,boost-python,pthread-join,Python,C++,Pthreads,Boost Python,Pthread Join,我正在开发一个python扩展,它使用pthread生成线程。在这个最小的示例中,生成的线程不会在python中连接回主线程。相反,在与C++可执行文件链接时运行库并没有问题。对于python扩展,pthread\u创建和pthread\u加入的安全方法是什么 我的python\u扩展.cpp是: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <boost/py
pthread
生成线程。在这个最小的示例中,生成的线程不会在python中连接回主线程。相反,在与C++可执行文件链接时运行库并没有问题。对于python扩展,pthread\u创建
和pthread\u加入
的安全方法是什么
我的python\u扩展.cpp
是:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
class myTestClass{
public:
myTestClass(){};
void *print_message_function(void *ptr);
void wrapperf();
}
void *myTestClass::print_message_function( void *ptr ){
char *message;
message = (char *) ptr;
printf("%s \n", message);
}
void myTestClass::wrapperf()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
}
// C Wrappers for the above C++ classes
#ifdef __cplusplus
extern "C" {
#endif
myTestClass *newcase(){ return new myTestClass};
#ifdef __cplusplus
}
#endif
// Boost python
BOOST_PYTHON_MODULE(mylib_py)
{
using namespace boost::python;
class_<myTestClass, boost::noncopyable>("myTestClass", init<std::string>())
.def("wrapperf", &myTestClass::wrapperf)
def("newcase", &newcase, return_value_policy<manage_new_object>());
}
有时,这方面的输出是:
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
有时只是:
Thread 1
Thread 2
而且这些线根本没有连接!我如何解决这个问题?这可能是因为在
obj.wrapperf()
完成之前,我的python脚本已经进入下一行x=2
。您的示例代码在控件返回python之前加入了它的线程。那么你的问题是什么?您是否试图创建与Python重叠的长时间运行线程?为什么使用C标题代替C++头文件?为什么要使用pthread
(除非您使用的是C++11之前的编译器)?@tedlynmo True,我从一个pthreads
因为它是最小的,而且我需要的所有线程都是异步的。我明白了。即便如此,我还是会尽快找到
和它的朋友。它应该使您的代码更加精简:-)和安全(RAII互斥锁等)。在pthread_create()和pthread_join()之间是否存在可能引发异常的东西??您的示例代码在将控件返回Python之前将其线程连接起来。那么你的问题是什么?您是否试图创建与Python重叠的长时间运行线程?为什么使用C标题代替C++头文件?为什么要使用pthread
(除非您使用的是C++11之前的编译器)?@tedlynmo True,我从一个pthreads
因为它是最小的,而且我需要的所有线程都是异步的。我明白了。即便如此,我还是会尽快找到
和它的朋友。它应该使您的代码更加精简:-)和安全(RAII互斥锁等)。在pthread_create()和pthread_join()之间是否存在可能引发异常的内容??
Thread 1
Thread 2