mercredi 21 octobre 2020

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 start_ 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
}

Aucun commentaire:

Enregistrer un commentaire