When i create three p_thread-> pt1, pt2, pt3, if pt2 achieve some condition such as global variable = 100 than I need to kill pt3 thread, Is it use pthread_exit() and pthread_join() or pthread_cancel() and pthread_testcancel()?
Asked
Active
Viewed 17 times
0
-
You might also want to look into [`std::thread`](https://en.cppreference.com/w/cpp/thread/thread) - it has a nicer, type-safe API. – Paul Sanders Jun 21 '22 at 10:43
-
2It's not a good idea to kill threads in a process, since that's an effective way to leave the containing process in an inconsistent state. The usual way is to somehow communicate with that thread (e.g send it a message in some way) and have the thread clean itself up when required to exit. That relies on their being some mechanism for communication (e.g. one thread can trigger an event, and another thread can recognise that the event was triggered so it can respond). – Peter Jun 21 '22 at 10:43
-
pthreads are not C++ threads, but are C-based threads. It is not realistically possible to "kill" a pthread in any non-trivial C++ program. All futile attempts to do so will always eventually end in tears. It is a foundational principle that underpins all of C++ that every created object gets destroyed, at some point. Canceling a thread, out of the blue, breaks that, taking down the entire C++ program, and library, with it. – Sam Varshavchik Jun 21 '22 at 11:04
-
@SamVarshavchik *Canceling a thread, out of the blue, breaks that, taking down the entire C++ program, and library, with it.* Or even worse leaves the process appearing to be OK but silently corrupting data. – Andrew Henle Jun 21 '22 at 12:20