dimanche 12 février 2023

Force kill a C++ thread which is stuck on some blocking function

I have std::thread which listens for netlink events from the Linux kernel, It has an infinite while loop and a blocking function which blocks until the next event. I want to stop the thread forcefully in the program workflow when I don't need that anymore.

Here is my current solution:

#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <thread>
#include <signal.h>

void thread_func() {
    while(true) {
        std::cout << "Processing events.." << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(10)); // simulating a blocking function that blocks until next events
        std::cout << "Events received.." << std::endl;
    }
}

int main() {
    std::thread eventListener(thread_func);
    std::this_thread::sleep_for(std::chrono::seconds(3)); // doing some work in main thread
    pthread_cancel(eventListener.native_handle()); // I don't want the eventListener anymore
    eventListener.join();
    std::cout << "eventListener killed" << std::endl;
    return 0;
}

My program only compiles to the Linux platform.

Questions:

  1. Is it the correct way of doing it in C++? or I'm missing some minor details here?
  2. Is there any other better way of achieving this?
  3. if I change the above code to kill the thread by pthread_kill instead of pthread_cancel then I don't see the print "eventListener killed" in output, I don't know why?

Aucun commentaire:

Enregistrer un commentaire