Boost shared_ptr question
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: Boost shared_ptr question

  1. #1
    Join Date
    Mar 2009
    Posts
    166

    Boost shared_ptr question

    Hello all,

    I have a class called Wheel, and I created a boost shared_ptr to this class in the following way:

    Code:
    typedef boost::shared_ptr<Wheel> WheelPtr;
    I also have a vector of these shared_ptr's to Wheels as so:

    Code:
    vector<WheelPtr> wheels;
    In the wheel class I have a variable called "flat" which is initialized to true.

    I have one thread that keeps iterating through the list looking for flat wheels like so:

    Code:
    vector<WheelPtr>::iterator it;
    for(it=wheels.begin(); it!=wheels.end();)
    {
         if(!(*it)->Flat())
         {
           (*it) = WheelPtr(); // set to NULL here
            it=wheels.erase(it);
         }
         else
              it++;
    }
    In another thread I am constantly doing something else to the wheels. What I have noticed is that when I execute the line:

    Code:
           (*it) = WheelPtr(); // set to NULL here
    in the debugger the handle is 0x00000000. But in my other thread the handle is something else like 0x00104f08.

    Why is the shared_ptr not NULL in the other thread?

    Regards,
    Ellay K.
    Last edited by ekhule; April 18th, 2013 at 08:42 AM.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,431

    Re: Boost shared_ptr question

    Quote Originally Posted by ekhule View Post
    I also have a vector of these shared_ptr's to Wheels as so:
    Where do you do any synchronization? Writing a threaded program doesn't just mean you call the function to launch a thread.

    A vector operations are not thread safe. If you're altering the vector at the same time you're reading from the vector, what do you think may/will happen?

    http://stackoverflow.com/questions/3...race-condition

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Apr 1999
    Posts
    27,431

    Re: Boost shared_ptr question

    Also, this accomplishes ridding yourself of flat tires:
    Code:
    #include <algorithm>
    //...
    bool IsTireFlat(const WheelPtr& theWheel)
    {   return theWheel->Flat(); }
    //...
    wheels.erase(std::remove_if(wheels.begin(), wheels.end(), IsTireFlat), wheels.end());
    No loops needed.

    But it still is the case that while you're altering the vector in one thread, no other threads should be attempting to read (or write) to the vector.

    Regards,

    Paul McKenzie

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center