想象我有以下几点:使用操作当前对象的线程安全吗?
struct A {
std::vector<int> _vect;
std::mutex _mutex;
void f() {
std::thread t1(&A::work, this);
std::thread t2(&A::work, this);
t1.join();
t2.join();
}
void work() {
std::vector<int> cvect;
while (true) {
bool keep = false;
_mutex.lock();
// get_next() modify the internal state of this
keep = get_next();
cvect = _vect; // copy of _vect
_mutex.unlock();
if (!keep) break;
// Do some stuff that does not require the `this`, e.g.:
std::sort(cvect.begin(), cvect.end());
int v = cvect.back() - cvect.front();
}
}
bool get_next() {
// This methods modify _vect
_vect = std::vector<int>{1, 2, 3, 4}; // e.g.
}
}
int main() {
A a;
a.f();
return 0;
}
以上编译和工程(用更复杂的实现)。
它是否安全(如果不是,我怎样才能使它安全?)?
期间
_work
可能发生什么错误(这情况下没有被正确处理?)?
'执行线程't1'和't2'时'A'对象生活。那么,为什么你认为你的代码不安全? – Tsyvarev
@Tsyvarev我不认为这是,但因为我以前从来没有操作'thread'和'mutex',我以为我可能已经忘记了一些东西...... – Holt
“不需要这个指针”意味着没有成员变量是访问? –