Running Threads in Python Extensions
I am trying to start a thread from my SWIG Python C ++ extension, however when I run it, it outputs this:
libc++abi.dylib: terminating
Abort trap: 6
I guess there shouldn't be any problem with the GIL since python allocated objects are not used. Or am I wrong in this assumption?
Minimal example:
// _MyExtension.cpp
#include <iostream>
#include <thread>
void threadFunc() {
std::cout << "Thread started" << std::endl;
std::this_thread::sleep_for (std::chrono::seconds(10));
std::cout << "Thread ended" << std::endl;
}
void start() {
std::thread first (threadFunc);
}
// _MyExtension.i
%module _MyExtension
%{
extern void start();
%}
extern void start();
// test.py
import _PyMapper
_PyMapper.start()
+3
source to share
1 answer
Easy fix, the stream needs to be detached after creation, e.g .:
void start() {
std::thread first (threadFunc);
first.detach();
}
Then it works great! However, the thread will be killed prematurely as soon as all statements are completed in the original Python script. This is fixed by adding a function call to your extension, which is attached to the stream.
0
source to share