I have a question regarding the term thread-safety. Let me give an example:
#include <mutex>
#include <vector>
/// A thread-safe vector
class ThreadSafeVector {
private:
std::mutex m;
std::vector<double> v;
public:
// add double to vector
void add(double d) {
std::lock_guard<std::mutex> lg(m);
v.emplace_back(d);
}
// return length of vector
int length() {
std::lock_guard<std::mutex> lg(m);
return v.size();
}
};
Would you call that class, i.e. all its methods, thread-safe?
EDIT [Sunday, 9 PM CEST]
After getting some good "yes, but"-answers and alternative implementations, I provided my own view in an answer below. Basically, it boils down to the simple question, whether thread-safety of a class only has to make strong atomicity and visibility guarantees for PARALLEL execution of its methods OR whether a class has to make guarantees that stretch beyond its own scope (for example SERIAL execution).
See Question&Answers more detail:os