0

When my application is about to close, should the UI thread "tell" the other threads to terminate, and wait for them to do so before closing the application?

  • 2
    Probably. It depends on what they are doing. – David Heffernan Jun 15 '15 at 16:55
  • 1
    Unless you detach the threads they would be killed when the process exits. However, you then have no control over how the threads exit or any cleanup, they would just be killed where they are which could problems. – Some programmer dude Jun 15 '15 at 16:59
  • 1
    @Joachim: How do you *detach the threads* (to keep them alive when their parent process dies)? – IInspectable Jun 15 '15 at 17:01
  • possible duplicate of [main thread exit, does other exit too?](http://stackoverflow.com/questions/11875956/main-thread-exit-does-other-exit-too) – moorray Jun 15 '15 at 17:30
  • @ShayGold You're talking about `std::thread` I guess? This question is tagged for `c` and `winapi` so I think Win32 threads are the subject at hand. – Jonathan Potter Jun 15 '15 at 17:56
  • If it will not cause deviations from your requirements, don't try to do this. The number of questions re. deadlocks and shutdown-failures from attempting to 'cleanly' shut down threads from UI event-handlers is considerable. You should only attempt it if you absolutely have to. – Martin James Jun 15 '15 at 20:25

1 Answers1

2

To clarify; when your main thread (the one that started with your process) returns from the WinMain function, the process will exit and all your other threads will terminate automatically.

It depends what your other threads are doing as to how important it is that you shut them down cleanly.

For example, if the other threads are potentially writing to disk, then you absolutely should shut them down cleanly. If they're just doing calculations then it probably wouldn't hurt to let them die automatically when your main thread exits.

However it's always good programming practice to clean up after yourself (free any memory allocations, etc).

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
  • 2
    It is not always good programming practice. It's often a waste of time and effort and is occasionally a very bad idea indeed. If you can get away without writing shutdown code, (and testing it, and debugging it), you should do so. If your app requirements don't care, or can handle, unflushed writes, who cares if some thread is writing to disk? – Martin James Jun 15 '15 at 20:29
  • 1
    I believe the usual expression is "you don't sweep the floor when the building is about to be demolished". :-) – Harry Johnston Jun 15 '15 at 22:33
  • It's not good to get into the habit of never sweeping the floor though. – Jonathan Potter Jun 15 '15 at 23:05
  • Nobody is suggesting that though. Just not sweeping at demolition time. – David Heffernan Jun 16 '15 at 06:06
  • I'm happy to agree to disagree on this one (and only this one :)) – Jonathan Potter Jun 16 '15 at 06:08