Gracefully teardown thread that handle XPC service

Hi, I’ve got an xpc service that is being handled by a specific thread that runs the following method :

upon c’tor, I start the xpc service in a new thread ;

class cppWrapperClass {

private: 
  std::thread t_;
  NSXPCListener *listener_;
  ServiceDelegateAlertsHandler *delegate_;

};

cppWrapperClass::cppWrapperClass() {
  std::thread t_ = std::thread(&startService, this);
}

void startService() {
  listener_ = [[NSXPCListener alloc] initWithMachServiceName:@"com.myapp.alerts"];
  delegate_ = [ServiceDelegateAlertsHandler new];
  listener_.delegate = delegate_;
  [listener_ resume];
  [[NSRunLoop currentRunLoop] run];
}

Now, i’d like to gracefully teardown the process before exiting.

So I’m looking for a way to terminate the thread, if it’s done directly from the wrapper destructor the process get crash with abort message, so I wonder if there’s any way to terminate the currentRunLoop from another thread in the process ?

Did you mean to assign that local variable to this->t_ ?

oops sorry, It should be class member

t_ = std::thread (&startService, this);

Btw, when I detach the thread from it’s task in the destructor, it seems to be working … it’s like the thread cannot be destructed white it execute the runLoop. does it make any sense ?

cppWrapperClass::~cppWrapperClass() {
  t_.detach()
}

I don’t know of an elegant way of terminating a thread while it’s running, but you should be able to send a signal to it or set a global flag which the tread checks regularly and exits when the flag is set.