Skip to content

Typical Mistakes Threads

vhirtham edited this page Jul 4, 2018 · 1 revision

Starting threads

If a new std::thread is started one have to specify a function which should be run. Most of the times one passes a lambda function to the threads ctor which could capture external variables. If those variables are not initialized correctly before the thread is constructed it results in undefined behavior. This is especially critical if a std::thread is part of a class where the initialization order is enforced by the declaration order. Even if all class variables are initialized correctly in the initializer list you might encounter undefined behavior if the thread is initialized before any variable that is used in the function passed to the thread. Try to always declare member threads after all other class members.

References

If a function with multiple parameters is passed to the constructor of std::thread, all arguments are copied, even if the function explicitly takes a reference or a pointer. To solve this problem, use std::ref to pass a reference.

Clone this wiki locally