Hi All,
I've just realized weak_ptr::lock is not thread safe. Is it expected behavior? Following sample reproduced this conclusion.
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/interprocess/detail/atomic.hpp>
#include <boost/interprocess/sync/interprocess_semaphore.hpp>
static volatile int v = 0;
boost::interprocess::interprocess_semaphore s1(0);
boost::interprocess::interprocess_semaphore s2(0);
boost::interprocess::interprocess_semaphore s3(0);
class SomeClass{
public:
boost::shared_ptr<SomeClass> s_this_;
boost::weak_ptr<SomeClass> w_this_;
SomeClass()
{
s_this_.reset( this );
w_this_ = s_this_;
v = 1;
}
void release()
{
s_this_.reset();
}
~SomeClass()
{
v = 0;
}
};
SomeClass *c;
void worker()
{
int counter = 0;
for( ;; )
{
s1.wait(); // wait for created object
boost::weak_ptr<SomeClass> w = c->w_this_; // make weak ptr
s2.post(); // let main thread go ahead
boost::shared_ptr<SomeClass> s = w.lock(); // create shared_ptr from weak_ptr
if( s ) // test for valid shared_ptr
{
if( 0 == v ) // if 0, object is destroyed
{
std::cout << "!!!!!!!! : " << counter << std::endl;
exit(1);
}
}
s3.post(); // notify main thread about test completion
++counter;
}
}
int main()
{
boost::thread t = boost::thread( &worker );
for( ;; )
{
c = new SomeClass(); // create object
s1.post(); // notify thread about new object
s2.wait(); // wait for thread to make weak_ptr
c->release(); // destroy object
s3.wait(); // wait for thread complete
}
return 0;
}
Best regards.
Dima
--
Dmytro Ovdiienko