1

I want to kill all currently running threads of a process when it receives a stop message. But I want the process to still keep running to accept new requests. I using c++ std::thread and not pthreads

mithu
  • 11
  • 3
  • 2
    Forward the stop message to all running threads and have them check for the message periodically and return if found. – user4581301 Aug 08 '17 at 21:54
  • The process has 1 more thread than the n threads it launched. I call this thread 'main()', and it continues to run until it exits. – 2785528 Aug 08 '17 at 21:58
  • You probably don't want to kill (terminate) the threads because they might be holding a lock or something else that will bugger up everything. You want to ask them nicely to terminate when they are at a good point. That means the threads need to check periodically if they should exit. – Jerry Jeremiah Aug 08 '17 at 22:03
  • Possible duplicate of [Kill Thread in Pthread Library](https://stackoverflow.com/questions/2084830/kill-thread-in-pthread-library) – MikeMB Aug 08 '17 at 22:08
  • Thanks for your comments. But I don't use pthread library – mithu Aug 09 '17 at 16:28
  • Yep added a stop flag and checked periodically. Works fine but is there a similar way to pause a thread and later make it proceed from where it stopped. I know sleeping until a condition is met is one solution – mithu Aug 10 '17 at 23:14

1 Answers1

2

In short: You can't kill threads in ISO c++. You can only e.g. repeatedly poll a flag inside the thread and stop further processing.

As std::threads are usually implemented on top of pthreads on linux, you might be able to leverage that API, e.g. have a look at pthread_cancel. Keep in mind however, that this won't trigger any c++ destructors, so you have to be very careful when you do this to avoid resource leaks.

MikeMB
  • 20,029
  • 9
  • 57
  • 102