How to stop thread from executing py::eval_file #4223
Answered
by
Chaojimengnan
Chaojimengnan
asked this question in
Q&A
-
I have a question about how to stop a thread when it is executing a python script. Like the following : #include <iostream>
#include <pybind11/embed.h>
#include <thread>
void thread1()
{
autopy::py::scoped_interpreter const guard {};
autopy::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 ?
std::cout << "ok\n";
std::this_thread::sleep_for(std::chrono::seconds(50));
return 0;
} |
Beta Was this translation helpful? Give feedback.
Answered by
Chaojimengnan
Oct 7, 2022
Replies: 1 comment
-
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;
}, nullptr);
}
std::cout << "ok\n";
std::this_thread::sleep_for(std::chrono::seconds(50));
return 0;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Chaojimengnan
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
OK, I finally found a solution, https://stackoverflow.com/questions/1420957/stopping-embedded-python
The code is as follows: