Search code examples
c++multithreadingpthreadsstdthread

Why c++ threads are movable but not copiable?


As the title of the question says, why C++ threads (std::thread and pthread) are movable but not copiable? What consequences are there, if we do make it copiable?


Solution

  • Regarding copying, consider the following snippet:

    void foo();
    
    std::thread first (foo);     
    std::thread second = first; // (*)
    

    When the line marked (*) takes place, presumably some of foo already executed. What would the expected behavior be, then? Execute foo from the start? Halt the thread, copy the registers and state, and rerun it from there?

    In particular, given that function objects are now part of the standard, it's very easy to launch another thread that performs exactly the same operation as some earlier thread, by reusing the function object.

    There's not much motivation to begin with for this, therefore.


    Regarding moves, though, consider the following:

    std::vector<std::thread> threads;
    

    without move semantics, it would be problematic: when the vector needs to internally resize, how would it move its elements to another buffer? See more on this here.