Search code examples
c++multithreadingluac++14infinite-loop

C++ terminate a thread without having acces to the function executed in the thread


I'm making a script handlers in C++14. I get function body in a lua script, that is suppose to be given by a client ( I use interpreter Sol/lua ), and exectute it in a thread. So my problems is if the client put a infinite loop (while true) in his script, I should be able to stop/kill the thread after 3 seconds.

I tryed with and detach() but the infinite thread keep running during the entire rest of my programme. Without detach(), SIGABRT is send and stop everything at the end of my scope.

#include <thread>
#include <chrono>

//function that i don't know the content.
//In the worst case, it's an infinite loop.
void infinitClientFunction() {
    while (true) {}
}

void callfunc() {
   std::thread t(infiniteClientFunction);
   t.detach();

   std::this_thread::sleep_for(std::chrono::milliseconds(3500));
   // I want t terminated/kill/stop here (if it is infinite).
}


int main(){
   callfunc();
   // But t still exist here.

   /*
   rest of my program.
   ...
   */
}

That's doesn't seem complicated but I'm stuck. Please help me. Have a nice day.

(EDIT) To specify, infiniteClientFunction is given by the client (by interpretting Lua Script but this is not the point). So if the client use a correct syntax and lexic but give an unlogic function, I should be able to stop it after a some time.


Solution

  • Nicol Bolas said, "C++ has no mechanism to kill threads." That's because there is no safe way to kill a thread in any language or in any OS. You can never be sure that, at the moment when the thread is killed, it hasn't left something in a bad state—e.g., left a mutex locked, left a data structure in an invalid state—that will prevent the rest of your program from functioning as it should.

    Running foreign code in your application always is a tricky proposition. The first step you can take toward doing it safely is to run the foreign code in a child process. Killing a process is much safer than killing a thread.