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.
Thanks.
const and Thread Safety The C++11 standard does not expect to be able to safely call non const functions simultaneously. Therefore all classes available from the standard, e.g. std::vector<>, can safely be accessed from multiple threads in the same manner.
This operation mutates state and therefore is not const , but the mutation is guaranteed to be atomic, and is therefore thread-safe.
So, it's considered to be thread-safe and can be safely called by multiple threads at the same time. All threads can safely call the factorial() method and will get the expected result without interfering with each other and without altering the output that the method generates for other threads.
Obviously, no STL data structure is thread-safe. But at least, with std::vector for example, you can simply use mutexes to protect access to the vector.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With