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()?
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:
epoll_wait
with a signal, after adding appropriate signal masks and logic for handling EINTR
epoll_pwait
and send that a signal