liveBook · Manning

Callable

As explained in C++ Concurrency in Action, Second Edition

A callable object is an object that can be invoked with function-call syntax.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains function-object copying and a declaration-parsing pitfall, but does not detail callable internals.
Examples
Demonstrates a function, an operator() class, a lambda, and ambiguous thread-construction syntax.
What you can do after
Apply callable functions, objects, or lambdas when constructing a std::thread.
How it connects
Connects callable objects with std::thread, function objects, and lambdas.

Also explained in

Compare how 5 books explain callable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.