Skip to content

Instantly share code, notes, and snippets.

@adbuerger
Created November 15, 2018 15:26
Show Gist options
  • Save adbuerger/ae9fc28474ed5117aa6c8b1dad55d152 to your computer and use it in GitHub Desktop.
Save adbuerger/ae9fc28474ed5117aa6c8b1dad55d152 to your computer and use it in GitHub Desktop.
Interrupt C++ function from Python (place pybind11 into the same folder, then compile using cmake . && cmake --build .)
#include "A.hpp"
A::A(int a_init)
: a(a_init),
interrupted(false)
{
}
A::~A(){
}
void A::solve(){
while (!interrupted) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
if (!interrupted) {
py::print(++a);
}
}
if (interrupted) {
std::cout << "Interrupted.\n";
}
}
void A::stop() {
std::cout << "Interrupting ... \n";
interrupted = true;
}
#include <chrono>
#include <thread>
#include <iostream>
#include <atomic>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
class A {
public:
A(int a_init);
~A();
void solve();
void stop();
std::atomic<bool> interrupted;
private:
int a;
};
cmake_minimum_required(VERSION 2.8.12)
project(a)
# Set source directory
set(SOURCE_DIR ".")
# Tell CMake that headers are also in SOURCE_DIR
include_directories(${SOURCE_DIR})
file(GLOB SOURCES ${SOURCE_DIR}/*.cpp)
set(${SOURCES})
# Generate Python module
add_subdirectory(pybind11)
pybind11_add_module(_a ${SOURCES} "${SOURCE_DIR}/PythonBindings.cpp")
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
set(CMAKE_CXX_FLAGS "-O3 -Wpedantic -Wextra")
#include "A.hpp"
PYBIND11_MODULE(_a, m)
{
py::class_<A>(m, "A")
.def(py::init<int>())
.def("solve", &A::solve)
.def("stop", &A::stop);
}
import signal
import threading
from _a import A
a = A(3)
def handle_interrupt(signum, frame):
if signum == signal.SIGINT:
a.stop()
signal.signal(signal.SIGINT, handle_interrupt)
a.solve()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment