Custom std::thread that ends only on signal

  c++, multithreading, stdthread

I already asked this question in another post, but it came out poorly, so I want to rephrase it better.

I have to start a series of thread doing different tasks, that only have to return if an exit signal was sent, otherwise (if they incur in exceptions or anything else) they just restart their code from beginning.

To make my intent clear, here’s some code:

class thread_wrapper
{
 public:
    template<typename _Callable, typename... _Args>
    thread_wrapper();

    void signal_exit() {exit_requested_ = true;}

    void join() {th_.join();}


 private:
    std::thread th_;

    bool exit_requested_{false};

    void execute()
    {
        while(!exit_requested_)
        {
            try
            {
                // Do thread processing
            }
            catch (const std::exception& e)
            {
                std::cout << e.what() << std::endl;
            }
        }

        return;
    }

};

What I want to achieve, is to use this class as it was a normal std::thread, passing a function and its arguments when it is initialized, but then I want the inner std::thread to run the "execute" function, and only inside the try block I want it to run the behaviour passed in constructor.

How could I achieve this? Thanks in advance.

Source: Windows Questions C++

LEAVE A COMMENT