2

I have a singleton like this:

class MySingleton{
public:
  void StartThread();
  static MySingleton& GetInstance(){
    static MySingleton st;
    return st;
  }

   // copied forbidden here
   ...
   //

private:
   // resources defined here
   ...
   //
};

void DoStuff(MySingleton*);

The function StartThread() starts a detached std::thread to execute DoStuff(MySingleton*), which utilizes resources owned by the singleton instance.

My question is: Is it guaranteed that the thread exits before the singleton destructs(when the program exit) so that no released resources are utilzed?

sakugawa
  • 117
  • 5
  • Avoid this sort of thing like the plague. When you think you've got all of the cases covered, you'll just find another. – user4581301 May 27 '21 at 04:33
  • 1
    Revisit why you need a detached thread. It will be a source of unexplained shutdown bugs unless you cleanly finish the thread before `main` exits. That is, you might as well join the thread as the end of `main` and not detach it. – Richard Critten May 27 '21 at 08:07

1 Answers1

3

I don't think so, no. According to this:

What happens to a detached thread when main() exits?

When the main exists the detached thread may continue, but the static variables will be destroyed. Pretty likely that you will then be causing undefined behaviour.

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175