Call function inside a lambda passed to a thread

前端 未结 1 1476
独厮守ぢ
独厮守ぢ 2021-01-16 11:26

I\'m trying to create a object that can be given a function and its parameters to his constructor. This class will then call the given function inside a lambda that is inste

相关标签:
1条回答
  • 2021-01-16 12:09

    As said in the comments, this compile fine with gcc-4.9 (and above), but if you need to use gcc-4.8 you can add parameters to the lambda in the worker constructor and pass the arguments via the std::thread constructor:

    class worker {
    public:
        template <class Fn, class... Args>
        explicit worker(Fn f, Args ...args) {
            t = std::thread([f](Args ...largs) -> void {
                    f(largs...);
            }, std::move(args)...);
        }
    private:
        std::thread t;
    };
    

    This will also create copy of the arguments in the lambda arguments, unlike the capture by reference you were using [&] that was probably incorrect in this case (see @Yakk comment).

    0 讨论(0)
提交回复
热议问题