Call function inside a lambda passed to a thread

风格不统一 提交于 2019-12-01 13:18: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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!