The only reason you aren't seeing a problem with that code is because it exits very quickly after ~B() is called, before the other thread gets a chance to be scheduled again. In a large program, shutdown might not be so fast. Try putting a sleep(1) at the end of B::~B() -- you'll see that the destructor is called with the background thread still running. On Fri, Mar 6, 2009 at 11:13 AM, Marc Vaillant <m...@jhu.edu> wrote:
> On Fri, Mar 06, 2009 at 09:52:07AM -0800, Kenton Varda wrote: > > On Fri, Mar 6, 2009 at 5:50 AM, marc <vaill...@cis.jhu.edu> wrote: > > > > Isn't this a common scenario in C++ for which stdlib provides a > simple > > solution, std::auto_ptr? std::auto_ptr is a lightweight class > designed > > to "RAIIify" pointers. What am I missing? > > > > > > Deleting the objects on shutdown is easy. The problem is that doing so > while > > another thread is still using them may crash the program. If your > program is > > careful to shut down all background threads before exiting, then it's > fine, but > > many people write code which isn't so clean, and some of these people > insist > > that libraries should not delete their objects at exit for exactly this > reason. > > I'm referring to having a static auto_ptr variable. I'm not familiar > with how this can manifest the danger you describe. Can you point it > out in the following example? > > > #include <pthread.h> > #include <memory> > #include <iostream> > > > class B > { > public: > ~B() > { > std::cout<<"destructor called"<<std::endl; > } > > int alive() > { > return 1; > } > > }; > > class A > { > public: > static std::auto_ptr<B> b; > }; > > std::auto_ptr<B> A::b(new B); > > void *threadFunc(void* p) > { > while(1) > { > std::cout<<A::b->alive()<<" "; > } > } > > int main() > { > pthread_t t; > int rc; > int p; > rc = pthread_create(&t, NULL, threadFunc, (void *)p); > sleep(1); > > return 1; > } > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Protocol Buffers" group. To post to this group, send email to protobuf@googlegroups.com To unsubscribe from this group, send email to protobuf+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/protobuf?hl=en -~----------~----~----~----~------~----~------~--~---