Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector, push_back from another thread crashing?

I have unexpected assertions faillures in my code using a checked STL implentation.

After some research, I narrowed down the problem to a push_back in a vector called from a different thread than the one in which the vector was created.

The simplest code to reproduce this problem is :

class SomeClass
    {
    private:
        std::vector<int> theVector;
    public:
        SomeClass () 
        {
            theVector.push_back(1); // Ok
        }


        void add()
     {
          theVector.push_back(1); // Crash 
     }
};

The only difference is that SomeClass is instanciated from my main thread, and add is called from another thread. However, there is no concurency issue : in the simplest form of code I used for troubleshooting nobody is reading or writing from this vector except the cases I mentioned above.

Tracing into the push_back code, I noticed that some methods from std::vector like count() or size() return garbage, when it's called from the other thred (method "add"), and correct values when called from the creating thread (in the constructor for example)

Should I conclude that std::vector is not usable in a multithreaded environement ? Or is there a solution for this problem ?

EDIT : removed volatile

EDIT 2 : Do you think it's possible that the problem doesn't lie in multithread ? In my test run, add is called only once (verified using a break point). If I remove the push_back from the constructor, I still crashes. So in the end, even with only one call to a vector's method, in a function called once make the assertion fail. Therefore there can't be concurency, or ... ?

like image 536
Dinaiz Avatar asked Dec 10 '10 14:12

Dinaiz


2 Answers

std::vector definitely is usable in a multi-threaded environment, provided you don't access the vector from two threads at once. I do it all the time without trouble.

Since vector isn't the problem, you need to look more closely at your synchronization mechanism, as this is most likely the problem.

I noticed that you marked the vector as volatile. Do you expect that making it volatile will provide synchronization? Because it won't. See here for more information.

EDIT: Originally provided wrong link. This is now fixed. Sorry for confusion.

like image 94
John Dibling Avatar answered Sep 30 '22 02:09

John Dibling


If you can guarantee that nobody is writing to or reading from the vector when you call push_back, there's no reason that it should fail. You could be dealing with higher-level memory corruption. You should verify that "this" points to a genuine instance of SomeClass, check it's other members, etc.

like image 26
Puppy Avatar answered Sep 30 '22 02:09

Puppy