jeudi 29 janvier 2015

Safely moving objects that run a lambda in a member thread that accesses other members

I have a class that has an std::thread member variable which runs a lambda function that depends on some other member variable.


Let me give an example:



struct C {
C() {
thread_ = std::thread([this]() {
while (running_) {
...
}
});
}
C(C&& rv) {
swap(rv);
}
void swap(C& rhs) {
std::swap(thread_, rhs.thread_); // step 1
std::swap(running_, rhs.running_); // step 2
}
std::thread thread_;
bool running_;
};

int main() {
C c;
C c2 = move(c); // Is c safely moved to c2?
}



  • What is a safe way to move such an object?

  • To which object is capture [this] going to point after the move operation.

  • Which object's running_ is accessed in the lambda's while loop after step 1 but before step 2?


Aucun commentaire:

Enregistrer un commentaire