std::thread management: usage and best practice

14,738

Solution 1

Bjarne Stroustrup shows some examples of using std::thread in his C++11 FAQ. The simplest example looks like this:

#include<thread>

void f();

struct F {
    void operator()();
};

int main()
{
    std::thread t1{f};  // f() executes in separate thread
    std::thread t2{F()};    // F()() executes in separate thread
}

In general, std::thread is not intended to be inherited from. You pass a function to execute asynchronously in the constructor.

If your compiler does not support std::thread, you could use Boost.Thread instead. It is fairly compatible, so you can replace it by std::thread once your compiler supports it.

Solution 2

One of the problems with using std::thread as an unadorned local variable is that it is not exception safe. I will admit that I am often guilty of this myself when demonstrating small little HelloWorlds.

However it is good to know exactly what you're getting into, so here is a more detailed explanation of the exception safety aspects of using std::thread:

#include <iostream>
#include <thread>

void f() {}
void g() {throw 1;}

int
main()
{
    try
    {
        std::thread t1{f};
        g();
        t1.join();
    }
    catch (...)
    {
        std::cout << "unexpected exception caught\n";
    }
}

In the above example, I have a "large" program, which "occasionally" throws an exception. Typically I want to catch and handle exceptions before they bubble up to main. However as a last resort, main itself is wrapped up in a try-catch-all. In this example I simply print out that something really bad has happened and quit. In a more realistic example you might give your client a chance to save work, or free up memory or disk space, launch a different process that files a bug report, etc.

Looks good, right? Unfortunately wrong. When you run this, the output is:

libc++abi.dylib: terminating
Abort trap: 6

I didn't give my client the notification that something went wrong before returning from main normally. I was expecting this output:

unexpected exception caught

Instead std::terminate() got called.

Why?

As it turns out, ~thread() looks like this:

thread::~thread()
{
    if (joinable())
        terminate();
}

So when g() throws, t1.~thread() runs during stack unwinding, and without t1.join() getting called. Thus t1.~thread() calls std::terminate().

Don't ask me why. It is a long story, and I lack the objectivity to tell it unbiasedly.

Regardless, you have to know about this behavior, and guard against it.

One possible solution is to go back to the wrapper design, perhaps using private inheritance as first proposed by the OP and warned against in other answers:

class CHandler
    : private std::thread
{
public:
    using std::thread::thread;
    CHandler() = default;
    CHandler(CHandler&&) = default;
    CHandler& operator=(CHandler&&) = default;
    ~CHandler()
    {
        if (joinable())
            join();  // or detach() if you prefer
    }
    CHandler(std::thread t) : std::thread(std::move(t)) {}

    using std::thread::join;
    using std::thread::detach;
    using std::thread::joinable;
    using std::thread::get_id;
    using std::thread::hardware_concurrency;

    void swap(CHandler& x) {std::thread::swap(x);}
};

inline void swap(CHandler& x, CHandler& y) {x.swap(y);}

The intent is to create a new type, say CHandler that behaves just like a std::thread, except for its destructor. ~CHandler() should call either join() or detach() in its destructor. I've chosen join() above. Now one can simply substitute CHandler for std::thread in my example code:

int
main()
{
    try
    {
        CHandler t1{f};
        g();
        t1.join();
    }
    catch (...)
    {
        std::cout << "unexpected exception caught\n";
    }
}

and the output is now:

unexpected exception caught

as intended.

Why choose join() instead of detach() in ~CHandler()?

If you use join(), then the stack unwinding of the main thread will block until f() completes. This may be what you want, or it may not be. I can not answer this question for you. Only you can decide this design issue for your application. Consider:

// simulate a long running thread
void f() {std::this_thread::sleep_for(std::chrono::minutes(10));}

The main() thread will still throw an exception under g(), but now it will hang during unwinding, and only 10 minutes later print out:

unexpected exception caught

and exit. Perhaps because of references or resources that are used within f(), this is what you need to have happen. But if it is not, then you can instead:

    ~CHandler()
    {
        if (joinable())
            detach();
    }

and then your program will immediately output "unexpected exception caught" and return, even though f() is still busy crunching away (after main() returns f() will be forcefully canceled as part of a normal shutdown of the application).

Perhaps you need join()-on-unwinding for some of your threads and detach()-on-unwinding for others. Perhaps this leads you to two CHandler-like wrappers, or to a policy-based wrapper. The committee was unable to form a consensus for a solution, and so you must decide what is right for you, or live with terminate().

This makes direct use of std::thread very, very low-level behavior. Ok for Hello World, but in a real application, best encapsulated away in a mid-level handler, either via private inheritance or as a private data member. The good news is that in C++11 that mid-level handler can now be written portably (on top of std::thread) instead of writing down to the OS or a 3rd-party lib as is necessary in C++98/03.

Solution 3

The recommendation is not to inherit from std::thread: it has no virtual method anyway. I would even recommend not to use composition.

The main issue with std::thread is that it will start a thread as soon as it is built (except if you use its default constructor). Therefore, a number of situations are fraught with peril:

// BAD: Inheritance
class Derived: std::thread {
public:
    Derived(): std::thread(&Derived::go, this), _message("Hello, World!") {}

    void go() const { std::cout << _message << std::endl; }

private:
    std::string _message;
};

The thread may execute go before _message is built, leading to a data race.

// BAD: First Attribute
class FirstAttribute {
public:
    FirstAttribute(): _thread(&Derived::go, this), _message("Hello, World!") {}

    void go() const { std::cout << _message << std::endl; }

private:
    std::thread _thread;
    std::string _message;
};

Same issue, the thread may execute go before _message is built, leading to a data race.

// BAD: Composition
class Safer {
public:
    virtual void go() const = 0;

protected:
    Safer(): _thread(&Derived::go, this) {}

private:
    std::thread _thread;
};

class Derived: Safer {
    virtual void go() const { std::cout << "Hello, World!\n"; }
};

Same issue, the thread may execute go before Derived is built, leading to a data race.


As you can see, whether you inherit or compose, it is very easy to unwittingly cause a data race. Using std::thread as the last attribute of a class would work... if you can ensure nobody derives from this class.

It thus seems better to me, for now, to recommend only using std::thread as local variables. Note that if you use the async facility, you won't even have to manage a std::thread by yourself.

Share:
14,738
Maxim Kumpan
Author by

Maxim Kumpan

Updated on June 26, 2022

Comments

  • Maxim Kumpan
    Maxim Kumpan almost 2 years

    I'm trying to figure out threads after using them a bit in Java and I'm a bit baffled. Two questions:

    • Can I extend my class from a thread or must I manage the thread from within the class via a handler?
    • How do I save said thread handler? std::thread in and of itself does not appear to name a type.

    Any prod in the right direction would be greatly appreciated.

    How do I interpret this message?

    src/CHandler.h:27:9: error: 'thread' in namespace 'std' does not name a type
             std::thread _thread;
             ^
    

    And here's my attempt at extending thread:

    src/CHandler.h:17:30: error: expected class-name before '{' token
     class CHandler : std::thread {
                                  ^
    

    Complete, troublesome header:

    #ifndef __projectm__CHandler__
    #define __projectm__CHandler__
    
    #include <set>
    #include <vector>
    #include <thread>
    
    #include "CListener.h"
    
    class CHandler {
        public:
            virtual bool subscribe(std::shared_ptr<CListener> aListener);
            virtual bool unsubscribe(std::shared_ptr<CListener> aListener);
    
            virtual bool hasSubscriber(std::shared_ptr<CListener> aListener);
    
            virtual ~CHandler() {}
    
        protected:
            std::thread _thread;
            std::vector<std::weak_ptr<CListener> > _subscribers;
            std::set<const CListener *> _subscribersSet;
    
            virtual void run();
    };
    
    #endif /* defined(__projectm__CDefaultHandler__) */
    

    Compiler version:

    bash-3.1$ g++ --version
    g++.exe (GCC) 4.8.1
    

    The makefile (a mess, I know - still learning this bloody thing):

    CC=g++
    
    OUTFILE=game
    
    BINDIR=bin
    SRCDIR=src
    OBJDIR=obj
    
    CFLAGS=
    LDFLAGS=-std=c++0x
    
    
    
    all: core
    
    # Ядро проекта.
    core: $(OBJDIR)/main.o $(OBJDIR)/CGame.o $(OBJDIR)/CHandler.o $(OBJDIR)/CListener.o
        $(CC) $(CFLAGS) $(wildcard $(OBJDIR)/*.o) -o $(BINDIR)/$(OUTFILE)
    
    $(OBJDIR)/main.o: $(OBJDIR)
        $(CC) $(LDFLAGS) $(SRCDIR)/main.cpp -c -o $(OBJDIR)/main.o
    
    $(OBJDIR)/CGame.o: $(OBJDIR)
        $(CC) $(LDFLAGS) $(SRCDIR)/CGame.cpp -c -o $(OBJDIR)/CGame.o
    
    $(OBJDIR)/CHandler.o: $(OBJDIR)
        $(CC) $(LDFLAGS) $(SRCDIR)/CHandler.cpp -c -o $(OBJDIR)/CHandler.o
    
    $(OBJDIR)/CListener.o: $(OBJDIR)
        $(CC) $(LDFLAGS) $(SRCDIR)/CListener.cpp -c -o $(OBJDIR)/CListener.o
    
    # Создаем директорию для объектов, если ее нет.
    $(OBJDIR):
        mkdir $(OBJDIR)
    
    main.o: $(SRC)/main.cpp
    
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    I'm using g++ from the mingw package via custom makefile. LDFLAGS=-std=c++0x. Include thread did not help. Simply declaring std::thread mythread still throws an error.
  • PeterT
    PeterT over 10 years
    @MaximKumpan which version of g++ do you use?
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    @PeterT, added g++ version to question.
  • juanchopanza
    juanchopanza over 10 years
    No need for the funny syntax: std::thread mythread(my_func); will do.
  • jcoder
    jcoder over 10 years
    This is the problem. mingw does not support std::thread on windows at this time as far as I know. It certainly didn't recently. The current version of visual c++ on windows does.
  • jcoder
    jcoder over 10 years
    Not answer to the question but some comments on that here programmers.stackexchange.com/questions/195639/…
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    No ice, adding -std=c++11 to CFLAGS did not help.
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    This looks well and good, but declaring std::thread _thread; returns error: 'thread' in namespace 'std' does not name a type
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    @jcoder, that sounds a fair bit more like the answer. I'll do some research. Meanwhile, if you're sure of it, post that as an answer.
  • Björn Pollex
    Björn Pollex over 10 years
    This likely means that you have some include screwed up. It is impossible to diagnose the error without full source code. Have you tried compiling the example I have posted? If it works, then you know its not your compiler. You should probably do some reading on how includes work in C++, as they are quite different from package imports in Java.
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    Good question. I'll try compiling that example and see if thread works in and of itself.
  • PeterT
    PeterT over 10 years
    @MaximKumpan btw. there seem to other versions of minigw that actually have working std::thread support like minigw-w64
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    No, it does not work. g++ -std=c++0x -o test test.cpp \\ test.cpp: In function 'int main()': \\ test.cpp:11:5: error: 'thread' is not a member of 'std'
  • Björn Pollex
    Björn Pollex over 10 years
    @MaximKumpan: I have updated my answer. As a workaround, you can use Boost.
  • Maxim Kumpan
    Maxim Kumpan over 10 years
    Nothing is more permanent than a temporary solution. But I don't think Boost will be a problem as a legacy threading solution. I'll give it a try. Thanks for the help.
  • mrflash818
    mrflash818 over 5 years
    For g++ (v4.9.2) in linux, I needed to add two flags to support <thread> and std::thread programs: -std=c++11 -pthread