Consider a class containing the following vector:
std::vector<std::tuple<double, double, double> > _data;
and the following member function:
inline double second(const unsigned int i) const
{
return std::get<1>(_data[i]);
}
Do I have the guarantee that this function is thread-safe (note that I return a copy of the double)?
If not, what would be a thread-safe version of this function?
This is not thread-safe if the std::vector
can be modified by another thread. To make it thread-safe, access to the std::vector
must be synchronized. A possible solution is to introduce a std::mutex
and associate it with the std::vector
instance. In this case, the std::mutex
would be a member variable of the class that contains the std::vector
:
#include <mutex>
class X
{
private:
std::vector<std::tuple<double, double, double>> data_;
mutable std::mutex data_mutex_;
public:
double second(const unsigned int i) const
{
// Note that 'operator[]' is not bounds checked.
// Recommend adding a check to ensure 'i' is
// within range or use 'at()'.
std::lock_guard<std::mutex> lk(data_mutex_);
return std::get<1>(data_[i]);
}
};
Note the addition of the std::mutex
makes the class non-copyable as it itself is non-copyable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.