Search code examples
c++multithreadingepoll

In C++, how to destroy a thread started with class member function and waiting on epoll properly?


As the question says, I have an class. Pesudo code is as following:

class MyClass
{
  MyClass() 
  { 
    epoll_fd = epoll_create(0);

    /*start a thread with MyClass::threadFunc() here */ 
    mythread = std::thread( &MyClass::threadFunc, this );
  }

  void threadFunc()
  {
    while( true )
    {
      int numEvents = epoll_wait( epoll_fd, ... );
      // some processing here
    }
  }

  ~MyClass()
  {
    mythread.join();
  }

  std::thread mythread;
  int epoll_fd;
}

int main()
{
  MyClass inst;

  // some processing

  return 0;
}

I would like to have the thread started in the constructor and end in the destructor. However, the thread has an while loop and waiting for events. Hence the join() would never return, would it? I wonder what's the best practice to end the thread execution in this case?

If I use a flag to let the while loop quit, it would only work when the epoll_wait returns. If there is no event, then the program stuck at join(), right? So in this case, do I have to add a wake up fd into the epoll monitor list and manually send a event to itself before calling join()?


Solution

  • I wonder what's the best practice to end the thread execution in this case?

    Tell the thread to exit and then join it. The mechanism is up to you.

    You could:

    • add a file descriptor to the interest list which you can use to wake up the poll (eg. a pipe, or eventfd, or whatever)
    • interrupt epoll_wait with a signal, after adding appropriate signal masks and logic for handling EINTR
    • switch to using epoll_pwait and send that a signal
    • add a timeout to your poll and check an (appropriately-synchronized) boolean variable to see if the thread should keep running
    • etc.