0

One can stop a thread by using pthread_join(). But let's imagine one's got many threads that perform a complicated task and may not stop at the same time. One of them may stop earlier (because it's got the needed result). But how to stop other threads which can be almost infinite? If one thread's found the right solution, there is no more left, so other threads will never succeed.

How to terminate all threads when one of them got the result and stopped?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • I believe this is a duplicate, but not certain enough to wield the mighty hammer: http://stackoverflow.com/q/12029180/10077 – Fred Larson Dec 23 '14 at 16:15
  • 1
    `pthread_join()` does not stop a thread - it waits until a thread stops on its own, and reaps the return value and other associated data structures. If you need to have a way to do an orderly shutdown on a thread, read up on `pthread_cancel()` and associated routines. In order to forcibly kill a running thread, you'll need to understand signal handling and e.g. `pthread_exit()`. – twalberg Dec 23 '14 at 16:40

1 Answers1

0

However you want. Probably the easiest way is to have a boolean variable protected by a mutex that is set when a solution is found and periodically checked. If a thread finds the variable set, that means some other thread found the solution and it should terminate.

Your question suggests that you are thinking about threads incorrectly. You don't need to "reach in" to a thread to make it terminate or do the right thing. You have to write the code so the threads do the right thing in the first place, doing only work that needs to be done and terminating when there's nothing for them to do. That way, you don't need to force them to do the right thing with some extra mechanism.

Also, just to clarify, pthread_join doesn't stop a thread. It just waits for a thread to terminate and cleans up after it.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • About `pthread_join()` I just meant if one doesn't use that the program will terminate but threads will live. I want my threads do difficult calculations. In fact, hashing. If one thread's just generated the _needed_ hash all threads must stop. If it hasn't all of them continue working. – ForceBru Dec 23 '14 at 16:15
  • 1
    @ForceBru If you terminate a program, all threads of that program will immediately stop execution, even if they haven't exited. – Sneftel Dec 23 '14 at 16:18
  • pthread_cancel and pthread_kill can be used to terminate a thread. – jim mcnamara Dec 23 '14 at 17:36
  • @jimmcnamara Yep. If those functions happen to do exactly what you want, you can use them. They're a bit harder to understand and use safely though, so I generally don't recommend them. – David Schwartz Dec 23 '14 at 17:52