Pass parameters to std::thread wrapper

后端 未结 4 1430
一个人的身影
一个人的身影 2021-02-09 09:26

I want to implement a small thread wrapper that provides the information if a thread is still active, or if the thread has finished its work. For this I need to pass the functio

4条回答
  •  一生所求
    2021-02-09 10:07

    The following is simple, elegant, and to my knowledge the most-correct of all current answers (see below):

    template < class Function, class... Args >
    ManagedThread::ManagedThread( Function&& fn, Args&&... args ) :
        mActive(false),
        mThread(
            [this]( auto&& fn2, auto&&... args2 ) -> void {
                mActive = true;
                fn2(std::forward(args2)...);
                mActive = false;
            },
            std::forward(fn), std::forward(args)...
        )
    {}
    

    The answer by DeiDei has a subtle but important flaw: the lambda takes the stack variables by reference, so if the thread starts, and tries to use, the stack variables after the constructor returns, you can get a stack-use-after-free error. Indeed, compiling with -fsanitize=address is typically sufficient to demonstrate the problem.

    The answer by O'Neill does not work when e.g. any arguments are lvalues, and is a bit clunky.

    The answer by jotik is close, but does not work when the arguments are lvalues either, nor if they are member functions.

提交回复
热议问题