30

I would like to use a class that manages a thread (or several threads). Using composition, this would look like:

class MyClass{
private:
    std::thread mythread;
    void _ThreadMain();
public:
    MyClass();
    // other fields
}

Because the default constructor for an std::thread is pointless, I would need to call it explicitly in MyClass constructor:

MyClass::MyClass() : mythread(&MyClass::_ThreadMain,this) {}

However, in this case the _ThreadMain method will be likely executed before MyClass is constructed, leading to any kind of weird behaviour. This is clearly unsafe. How can I fix this?

An obvious solution would be to use a pointer to std::thread instead, and add another member function:

void MyClass::Start(){
    // This time mythread is of type  std::thread*
    mythread = new std::thread(&MyClass::_ThreadMain,this); // One could use std::unique_pointer instead.
}

which would fire up that thread. In this case it would be called after the class is constructed, which will be indeed safe.

However, I am wondering if there is any reasonable solution that would allow me not to use pointers for this. It feels like it should be possible somehow (hey, there must be a way to launch a thread when a class is constructed!), but I cannot come up with anything that would not cause troubles.

I have considered using a conditional variable so that the _ThreadMain waits till the constructor has done its work, but I cannot use one before the class is constructed, right? (This would also be unhelpful if MyClass was a derived class)

rafalcieslak
  • 915
  • 1
  • 12
  • 25
  • 9
    Omit the `new` at `mythread = new std::thread(&MyClass::_ThreadMain,this);`, `std::thread` is movable! Consider `std::bind` to bind your class member function. – πάντα ῥεῖ May 11 '14 at 15:14
  • 1
    You can let the thread wait (at the very start) until it's told to proceed. – Cheers and hth. - Alf May 11 '14 at 15:19
  • 1
    The problem here is that if the `_ThreadMain` method is virtual, the thread will call the wrong function. I'd be very interested in seeing a solution to this where the constructor does the right thing. – Alexandre C. May 11 '14 at 15:20
  • 4
    You're using a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris May 11 '14 at 15:20
  • 1
    possible duplicate of [C++11: std::thread inside a class executing a function member with thread initialisation in the constructor](http://stackoverflow.com/questions/5956759/c11-stdthread-inside-a-class-executing-a-function-member-with-thread-initia) – Klaus May 11 '14 at 15:46

3 Answers3

17

You can use a thread in combination with move semantics:

class MyClass final
{
private:
    std::thread mythread;
    void _ThreadMain();
public:
    MyClass()
        : mythread{} // default constructor
    {
        // move assignment
        mythread = std::thread{&MyClass::_ThreadMain, this};
    }
};

The move assignment operator is documented on the following page. In particular, it is noexcept and no new thread is created.

nosid
  • 48,932
  • 13
  • 112
  • 139
  • When you move a thread object does it start a new thread of execution, or does it actually move it? – Ben May 11 '14 at 15:16
  • 3
    This solution can run into trouble, if there are is a vtable pointer! The vtable pointer will be initialzed *after* the block of the constructor! – Klaus May 11 '14 at 15:16
  • @Klaus: You are right. However, you can run into all kind of trouble when using threads. I have made the class _final_ now. – nosid May 11 '14 at 15:26
  • Final will not help. If your class derives from a class with a virtual function every call to this virtual function will go to the base class version of the function until the vtable pointer was initialized. The only way to get this work is to forbid that the class itself has virtual functions or derives from a class with virtual functions. Maybe some SFINAE or static_assert tricks can test for that. – Klaus May 11 '14 at 15:33
  • 2
    @Klaus: In the body of constructor for class `T`, the dynamic type is `T`. So `final` does help very much with safety, but at the cost of preventing customization by overriding member functions. I think this solution is therefore not very general. – Cheers and hth. - Alf May 11 '14 at 15:35
  • This is the actual answer, ie. starting the thread later on without using a pointer to std::thread. OP doesn't want to start the thread in the constructor anyways. – Hugo Maxwell May 17 '19 at 06:53
  • @πάνταῥεῖ could you elaborate on the templates you're referring to? – Matthieu Apr 14 '22 at 13:17
11

There is no better way, in general, than having a separate Start function.

Suppose MyClass is a base class for some future (unknown) class Derived. If the thread is started while (or before) the MyClass constructor runs, it always risks calling the "wrong" implementation of some virtual function overridden by Derived.

The only way to avoid this is to have the thread wait until after Derived is fully constructed, and the only way to do that is to call some other function after the Derived constructor completes to tell the thread to "go"... Which means you must have some kind of separately-invoked Go function.

You might as well just have a separately-invoked Start function instead and forego the complexity of waiting.

[Update]

Note that, for complex classes, "Two-Phase Construction" is an idiom recommended by some. Starting the thread would fit seamlessly into the "initialization" phase.

Nemo
  • 70,042
  • 10
  • 116
  • 153
1

Consider separating the task from the thread management and launching.

One class creates a runner and any synchronization primitives snd the like, The other handles launching it. This allows construction of the runnable to fail before threading starts.

It also means the runnable is fully constructed prior to it being run.

Now a first pass would have the runner be a std::thread, but some stuff helping with abort and cleanup and continuations can be useful.

The run object could be a simple callable, or could add extra supportmfor the runnable to interact with it.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524