Pass parameters to std::thread wrapper

后端 未结 4 1431
一个人的身影
一个人的身影 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:17

    O'Neil and DeiDei got here first, and they're correct as far as I can tell. However, I'm still posting my solution to your problem.

    Here's something that would work better:

    #include 
    #include 
    #include 
    
    class ManagedThread {
    
    public: /* Methods: */
    
        template 
        explicit ManagedThread(F && f, Args && ... args)
            : m_thread(
                [func=std::forward(f), flag=&m_active](Args && ... args)
                        noexcept(noexcept(f(std::forward(args)...)))
                {
                    func(std::forward(args)...);
                    flag->store(false, std::memory_order_release);
                },
                std::forward(args)...)
        {}
    
        bool isActive() const noexcept
        { return m_active.load(std::memory_order_acquire); }
    
    private: /* Fields: */
    
        std::atomic m_active{true};
        std::thread m_thread;
    
    };
    

    It makes use of lambdas instead, and correctly uses std::atomic instead of volatile to synchronize the state, and also includes the appropriate noexcept() specifiers.

    Also note, that the underlying std::thread is not joined or detached properly before destruction, hence leading to std::terminate() being called.

    I rewrote the test code as well:

    #include 
    #include 
    
    int main() {
        ManagedThread mt1(
            []() noexcept
            { std::this_thread::sleep_for(std::chrono::milliseconds(500)); });
        std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive()
                  << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout << "thread 1 active = " << std::boolalpha << mt1.isActive()
                  << std::endl;
    }
    

提交回复
热议问题