Skip to content

How to stop thread from executing py::eval_file #4223

Discussion options

You must be logged in to vote

OK, I finally found a solution, https://stackoverflow.com/questions/1420957/stopping-embedded-python

The code is as follows:

#include <iostream>

#include <pybind11/embed.h>
#include <thread>

void thread1()
{
    py::scoped_interpreter const guard {};
    py::eval_file("1.py"); // It takes a long time

    std::cout << "over!\n";
}

int main()
{
    std::jthread my_thread(thread1);
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::cout << "stop!\n";

    // How do I stop thread1 from executing py::eval_file ? 
    {
         py::gil_scoped_acquire acquire;
         Py_AddPendingCall([](void*) {
             PyErr_SetString(PyExc_Exception, "Exit!");
             return -1;…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by Chaojimengnan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant