boost::shared_ptr<resource> resource_ptr;
boost::mutex resource_mutex;
void test()
{
if(!resource_ptr) //#1
{
boost::lock_guard<boost::mutex> lk(resource_mutex);
if(!resource_ptr) //#2
{
resource_ptr.reset(new resource); //#3
}
}
resource_ptr->do_something();
}
int main()
{
boost::thread t1(test);
boost::thread t2(test);
t1.join();
t2.join():
return 0;
}
According to the text book, this kind of codes may cause race condition, but I don't know why?
If t1 thread initialize the resource_ptr(#3) when t2 haven't gotten into #1
then t2 may or may get true at #2
if t2 get true at #2, the resource have already been initialize, so it would not be initialized again
No matter how hard I try, I can't see why "double-checked locking" would cause race condition?
Thank you very much