vendredi 17 juillet 2020

Calling detach() at the end of the thread

I have a working thread similar to the following code. In begin_work, it will check whether the working thread is executing before creating a new working thread. However, begin_work will never create the next working thread when the current thread is exited until I call end_work.

I have tried to call detach at the end of the thread and it works fine. Is it safe to call detach at the end of the thread? Or, how can I do to safely create the next working thread without calling end_work before calling begin_work?

class thread_worker {
private:
    std::thread worker;
    // ... other menbers

public:
    thread_worker() {};
    ~thread_worker() { end_work(); };

    void begin_work() {
        if (!worker.joinable()) {
            worker = std::thread { &thread_worker::do_work, this };
        }
    }

    void do_work() {
        // ... access other members ...

        if (exit not by notify) {
            worker.detach();    // can I call detach?
        }
    }

    void end_work() {
        if (worker.joinable()) {
            // notify worker to exit
            worker.join();
        } 
    }
};

Aucun commentaire:

Enregistrer un commentaire