Boost logo

Boost Users :

From: Tristan King (tristanking_at_[hidden])
Date: 2004-06-10 21:45:34


Hi,
I'm having trouble getting shared_ptr objects and threads to work in
harmony.
It may just be that i don't know enough about threads to solve this, but
i'm getting undefined behaviour in the code posted at the end of this mail.
i'm not worried about the order that the threads run in (as this is just
an example of the problem i'm having in a simple multi-threaded web
server i'm working on), but it seems like the shared_ptr object may be
getting deleted before the last thread gets to execute.
i.e. some sample output i'm getting is

0
1
3
4
-572662307

and

1
2
3
3
-572662307

i think i'm probably missing some mutex's or something, but i can't
figure it out
can anyone give me any pointers on how to get around this problem?

thanks in advance
--Tristan

#include <iostream>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

struct simple_thread : public boost::noncopyable
{
   simple_thread( boost::shared_ptr<int> i )
       : m_i( i )
   {}

   void operator( )( )
   {
       std::cout << (*m_i) << std::endl;
   }

   boost::shared_ptr<int> m_i;

};

int main( )
{

   boost::thread_group threads;

   for ( int i = 0 ; i < 5 ; ++i )
   {
       boost::shared_ptr<int> p( new int(i) );
       simple_thread trd( p );
       threads.create_thread( boost::ref( trd ) );
   };

   threads.join_all( );

   return 0;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net