Search code examples
c++multithreadingc++11move

Is that the thread object can be moved in C++ 11 reasonable?


In C++11, the thread object can be moved. As we all know, every thread we created owns a functor. Obviously, to move a thread which its functor has not been executed is reasonable. But what about moving a thread of which functor is being called or has been executed for some time?
To step further, if I implements a thread wrapper class, like:

//noncopyable is a tag class of which copy constructor and copy assignment are deleted.
class Thread:noncopyable{
private:
    using ThreadFunc = std::function<void()>;
    bool started_;    //used to mark whether the functor executes or not
    std::thread thread_;
    CountDownLatch latch_;
    std::string name_;
    ThreadFunc func_;
    ...
public:
    Thread(ThreadFunc func, const std::string& name)
      :func_(std::move(func)),name_(name){}
    ...
}

And I want to implement move operation for Thread as thread object does. Would check out the started_ before move operation be a better choice?(Although I think it would be ten to one not) Like:

Thread& Thread::operation=(Thread&& rhs) noexcept{
    if(this != &rhs && !started_){
        //do something
    }
    return *this;
}
Thread::Thread(Thread&& rhs) noexcept{
    //do something
}

Solution

  • A std::thread does not formally own the functor it was constructed with. Rather, the functor is held by the invocation of std::invoke which is kicked off (in the target thread) by the constructor.

    So moving a std::thread doesn't need to, and isn't going to, move the functor. As long as the thread is executing, the functor is alive as a local variable.