std::vector, thread-safety, multi-threading
I am using std::vector as shared data in a multi-threaded application. I encapsulate the thread inside a class, e.g.,
class ABC {
public:
double a, b, c;
};
boost::mutex mutex1;
class XYZ {
public:
XYZ(vector<ABC> & pVector) {
ptrVector = &pVector;
m_thread = boost::thread(&XYZ::Start, this);
}
~XYZ() {}
void Start();
public:
vector<ABC> * ptrVector;
boost::thread m_thread;
};
void XYZ::Start() {
try {
while(1) {
boost::this_thread::interruption_point();
for (unsigned int i=0; i<ptrVector->size(); i++) {
{
boost::mutex::scoped_lock lock(mutex1);
ptrVector->at(i).a = double(rand())/10000;
ptrVector->at(i).b = double(rand())/10000;
ptrVector->at(i).c = double(rand())/10000;
}
}
}
}
catch(boost::thread_interrupted) {}
catch(std::exception) {}
}
When I close the application, sometimes, in the debug, there will be 2 error messages, sometimes there will be no error messages. I often heard people talking about std::vector being not thread-safe, is this one of the cases? I am using Visual Studio 2008, boost thread, the size of the vector is fixed. Can anyone also offer some advice on how to use std::vector in a multi-threaded application.
- First-chance exception at 0x7688b9bc in ETP.exe: Microsoft C++ exception: std::out_of_range at memory location 0x02d8f7bc..
- First-chance exception at 0x00e916e0 in ETP.exe: 0xC0000005: Access violation reading location 0x00000008.
- Second Chance Assertion Failed: File c:\program files (x86)\microsoft visual studio 9.0\vc\include\vector, Line Second Chance Assertion Failed: File c:\program files (x86)\microsoft visual studio 9.0\vc\include\vector98
Thanks.
Solution 1:
Actually, it is absolutely pointless to state X
is or is not thread-safe! You need to qualify for what kind of uses. For example, hardly any class will be "thread-safe" when it is somehow used in one thread and destroyed in another.
That said, the statement that std::vector<T>
is not thread- safe, independent of how often it is repeated, is wrong. However, it seems most people neither understand nor appreciate the thread-safety guarantees given. std::vector<T>
is thread-safe in the following sense:
- You can read a vector object from multiple threads simultaneously.
- If there is one thread changing a vector object, there shall be neither concurrent readers or writers.
- Accesses to a vector object don't interfere with other vector objects.
This applies to vector structure itself. Accesses to contained object are bound to whatever rules are imposed on them. These are apparently not the thread-safety guarantees many people have in mind but anything stronger won't work with the container interface.
Solution 2:
You call ptrVector->size()
without locking it first. This could easily be the cause of your problems. Make sure to lock your vector before any reads or writes.