在此之前:我不是开发人员,我可能不理解你的一些消息,因为英语不是我的母语,我的问题可能很难理解.
考虑:
class MyVector
{
std::vector<command> vec;
std::mutex vector_m;
public:
void MVpush_back(command t)
{
this->vector_m.lock();
this->vec.push_back(t);
this->vector_m.unlock();
}
};
Run Code Online (Sandbox Code Playgroud)
command 是一个自定义类(它的内容在这里似乎不相关;复制构造函数确实存在).
基本上,因为我有很多可能的作家和读者,所以我想强制使用mutex访问vec参数.
由于我只使用push_back(),erase()而且find() 我可以重新定义它们,但我不知道是否有一种方法不必重新定义的所有功能.
就像是:
<template> safe(*function name*<template>)
{
this->vector_m.lock();
<template> retval = vec.*function name*<parameter>;
this->vector_m.unlock();
return retval;
}
Run Code Online (Sandbox Code Playgroud)
调用函数的地方是一种参数......
我认为它可以使用,std::initializer_list<type>但类型要求是阻止.
有没有办法做这样的事情?
重新提问:有没有办法用参数(1)作为函数(2)的参数来推动函数,并使函数(2)调用函数(1)?
如果您不介意牺牲成员访问运算符 ( ) 的使用.,则可以将所有向量操作整齐地包装为可锁定操作。
class MyVector {
std::vector<command> vec;
std::mutex vector_m;
struct locker {
MyVector& _ref;
locker(MyVector& parent) : _ref(parent) {
_ref.vector_m.lock();
}
~locker() { _ref.vector_m.unlock(); }
std::vector<command>* operator->() && { return &_ref.vec; }
};
public:
locker operator->() { return {*this}; }
};
Run Code Online (Sandbox Code Playgroud)
现在,对底层向量的每次访问都将在操作期间锁定和解锁向量:
MyVector mv;
mv->push_back(/* ... */);
// This locks the mutex before doing the push back
// And unlocks it immediately after, even in the face of exceptions.
Run Code Online (Sandbox Code Playgroud)
神奇之处在于operator->以传递的方式行事。它应用于自身的返回值,直到返回常规指针,然后像往常一样访问该指针。但沿途的每个临时变量都是按照后进先出的顺序创建和销毁的。因此临时MyVector::locker对象的生命周期或多或少只是访问的持续时间。