Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

c++ - Thread-safe vector: Is this implementation thread-safe?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IMHO:

This is both safe and useful:

  void add(double d) {
    std::lock_guard<std::mutex> lg(m);
    v.emplace_back(d);
  }

This is safe but useless:

  // return length of vector  
  int length() {
    std::lock_guard<std::mutex> lg(m);
    return v.size();
  }   

Because by the time you've got your length it may well have changed, so reasoning about it is unlikely to be useful.

How about this?

template<class Func>
decltype(auto) do_safely(Func&& f)
{
  std::lock_guard<std::mutex> lock(m);
  return f(v);
}

called like this:

myv.do_safely([](auto& vec) { 
  // do something with the vector
  return true;  // or anything you like
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...