Ok, thanks. There are other problems though. If A::b was a B* instead
of a std::auto_ptr<B>, then the data that A::b points to will be ok
because it won't be deleted. However, A::b would get deleted so access
to the data via A::b may be undefined.
Also I found that static vars local to the thread function get deleted
before the thread gets killed.
Static is dangerous in multithreaded scenarios for obvious reasons.
These issues just add more complications.
On Fri, Mar 06, 2009 at 11:44:58AM -0800, Kenton Varda wrote:
> 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
> > solution, std::auto_ptr? std::auto_ptr is a lightweight class
> > to "RAIIify" pointers. What am I missing?
> > Deleting the objects on shutdown is easy. The problem is that doing so
> > 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
> > that libraries should not delete their objects at exit for exactly this
> 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
> int alive()
> return 1;
> class A
> static std::auto_ptr<B> b;
> std::auto_ptr<B> A::b(new B);
> void *threadFunc(void* p)
> std::cout<<A::b->alive()<<" ";
> int main()
> pthread_t t;
> int rc;
> int p;
> rc = pthread_create(&t, NULL, threadFunc, (void *)p);
> 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 firstname.lastname@example.org
To unsubscribe from this group, send email to
For more options, visit this group at