jeudi 31 décembre 2020

std::thread arguments are copied on the new thread?

I have started reading "C++ Concurrency in action, seconds edition" by Anthony Williams. In its 2.2 section he writes that arguments to the thread function are copied on the new thread. I checked this on a couple of compilers, and it is true: if we pass an lvalue - it is copied on the new thread.

Anthony writes that this may represent undefined behaviour - lvalue may go out of scope on the original scope, while new thread starts up.

This is kind of scary. Does this mean that every std::thread constructor invocation has a potential race? Why this copying is not synchronized prior to returning from std::thread constructor? Why it is not copied on the original thread altogether?

Aucun commentaire:

Enregistrer un commentaire