Search code examples
c++multithreadingc++17stdthread

Have a thread own the functor it runs C++


If you want to run a functor in a new thread in c++ you have to create the functor object and then pass a reference to it into the thread constructor. This works but leaves you with a thread and the functor object as separate things. Is it possible to have a thread that owns the functor itself that will get cleaned up when join is called on the thread? A possible API could be something like thread<FunctorType>(args, for, functor) that will create the functor object within the thread class and then run it.


Solution

  • Yes, ofcourse. The constructor

    template< class Function, class... Args >
    explicit thread( Function&& f, Args&&... args );
    

    accepts a function object as a forwarding reference. This implies it will move the function if you provide it an rvalue.

    E.g.

    #include <thread>
    #include <iostream>
    
    struct F
    {
        auto operator()() { std::cout << "Hello World" << std::endl; }
    };
    
    auto test()
    {
        std::thread t1{[]{ std::cout << "Hello World" << std::endl; }};
    
        std::thread t2{F{}};
    
        t1.join();
        t2.join();
    }