A callable can be invoked with function-call syntax. In C++, std::thread accepts callable types, including functions and objects with a function-call operator. When a function object is passed to a thread, it is copied into the new thread’s storage and invoked there, so its copy should behave like the original. section 2.1.1
class background_task
{
public:
void operator()() const
{
do_something();
do_something_else();
}
};
background_task f;
std::thread my_thread(f);
A class with operator() can supply the work for a thread; the object is copied into the thread. section 2.1.1
Common callable forms and a syntax pitfall:
- A function can be passed directly to std::thread. section 2.1.1
- A lambda can provide the work inline. section 2.1.1
- std::thread my_thread(background_task()); can be parsed as a function declaration rather than an object definition. Extra parentheses or brace initialization avoid this ambiguity. section 2.1.1
std::thread my_thread((background_task()));
std::thread my_thread{background_task()};
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":21},{\"line\":0,\"ch\":22}],[{\"line\":1,\"ch\":37},{\"line\":1,\"ch\":38}],[{\"line\":0,\"ch\":39},{\"line\":0,\"ch\":40}],[{\"line\":1,\"ch\":38},{\"line\":1,\"ch\":39}],[{\"line\":1,\"ch\":21},{\"line\":1,\"ch\":22}],[{\"line\":1,\"ch\":39},{\"line\":1,\"ch\":40}]]"}
!@%STYLE%@!
These alternatives use extra parentheses or braces to ensure my_thread is declared as an object. section 2.1.1




