6

In the "C++ concurrency in action" book there is an example:

    class background_task
    {
    public:
        void operator() () const {
            do_something();
            do_something_else();
        }
    };

    background_task f;
    std::thread my_thread(f);

Followed by the text: "In this case, the supplied function object is copied into the storage belonging to the newly created thread of execution and invoked from there. It's therefore essential that the copy behave equivalently to the original, or the result may not be what's expected."

Could someone please explain to me in more details what these two sentences mean? What about other callable types that can be supplied to the thread object's constructor, are they not copied? How do I make sure that "the copy behave equivalently to the original" or why would it not behave equivalently? Thank you!

2 Answers 2

3

The statement is contrasting the given example with the case immediately before where a normal function void do_some_work(); is passed as an argument to std::thread.

std::thread my_thread(do_some_work);

The function object background_task f should be copyable. This is not possible if the class background_task consists of something that makes it non-copyable. For example, if background_task has a std::mutex, it will not be copyable because std::mutex is not copyable or movable. See Demo.

The second thing is that even if background_task is copyable, it should be ensured that the copy constructor produces an exact copy of the original. An example of where this does not happen is the well-known case where the class has raw pointers and the copy constructor does not do a deep-copy.

The callable void do_some_work(); is also copied into the thread like the function object, but does not face the issues mentioned above.

Sign up to request clarification or add additional context in comments.

Comments

0

There's nothing much to read into here.

The callable, whatever it is, must be copied into the thread, otherwise invoking it will not be thread-safe.

And if the callable is of a type that has shall-we-say "unexpected" copy semantics (think a really weirdly written copy constructor) then that's just bad news all around for anyone trying to use your code.

That's it!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.