1

In my program I have a static object that creates a boost::thread. The thread is supposed to run until program termination, but it shouldn't be terminated in random state, so I implemented controled thread termination in this static object's destructor. The problem is that when main() terminates my thread is terminated before the destructor is called.

Now the question: is it possible to prevent the thread to be destroyed? Or at least delay it, so that it happens after the destructor is called?

Tomasz Grobelny
  • 2,666
  • 3
  • 33
  • 43
  • 1
    Starting threads before entering `main` is somewhat dangerous, can't you just move this object/change your design? – K-ballo Nov 03 '11 at 21:20
  • 1
    The thread is created _after_ entering `main`. The static object is not global; it is in static get() method of the class (singleton). – Tomasz Grobelny Nov 03 '11 at 21:24

1 Answers1

0

Move the termination from the destructor to a function and simply call it before main ends.

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • 1
    I would prefer my library to be responsible for cleanup and not move that responsibility to its users. This would create room for subtle bugs. – Tomasz Grobelny Nov 03 '11 at 21:34
  • 2
    @Tomasz Grobelny: Use `std::atexit` then. – K-ballo Nov 03 '11 at 21:40
  • Relying on static destructor is not very good. If your library is implemented as a dll loading / unloading will call static object constructor/destructor. Giving user full control is the best option. The C++ standard doesn't talk about static object destructors and how they behave with threads – parapura rajkumar Nov 03 '11 at 22:08
  • I might be wrong but IIRC the standard talks that destructors should be run in reverse order than constructors. Of course it doesn't specify what happens with threads - that is obviously an implementation detail that apparently works differently on Windows/Unix. So the question is how to make the code behave on Windows the same way it does on Unix. That is: do not care about threads until all standard C++ code (in particular destructor) is executed. – Tomasz Grobelny Nov 03 '11 at 22:21
  • 1
    @K-ballo: Unfortunately `atexit` doesn't work as expected. And it seems nothing can be done about it: http://blogs.msdn.com/b/oldnewthing/archive/2007/05/03/2383346.aspx – Tomasz Grobelny Nov 04 '11 at 19:41