我有一个在两个并发线程之间共享的资源。该资源包含两个线程需要读取和写入的向量。因此,我通过互斥体访问该向量。迄今为止,资源共享运作良好,没有任何问题。复制构造函数相关的编译器错误
但是,当我尝试按如下方式为sharedResource编写一个拷贝构造函数时,问题就开始了。
class sharedResource{
public:
sharedResource(){}
sharedResource(const sharedResource &other) {
vec = other.GetVec();
}
std::vector<int> GetVec() const {
std::lock_guard<std::mutex> lock(vecMutex); // Gives error
return vec;
}
private:
std::vector<int> vec;
std::mutex vecMutex;
};
int main()
{
sharedResource bacon1;
sharedResource bacon2 = bacon1;
return 0;
}
对于这个代码,我得到错误
error C2664: 'std::lock_guard<std::mutex>::lock_guard(const std::lock_guard<std::mutex> &)' : cannot convert argument 1 from 'const std::mutex' to 'std::mutex &'
能否请您解释一下为什么我收到错误,如果有使用互斥没有得到编译器错误的方式。
如果一切都失败了,我将创建一个线程不安全的GetVec2成员函数,该函数将返回vec而不通过lock guard。但我想避免这种可能性。
std::vector<int> GetVec2() const {
return vec;
}
如果您将互斥锁声明为“可变”,该怎么办? – PaulMcKenzie
@PaulMcKenzie不知道这是一个选项 –
请检查您的代码是否传递*副本*互斥量与传递*引用*。处理引用时,请记住方法的任何“常量”。 –