Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ kill method without constantly checking flags

I have several work functions, that call accessory functions that might have something bad happen. I want to be able to stop the work functions if an accessory function determines something bad happened, without putting numerous flag checks in the work functions. For example,

struct Worker {
    bool badhappened = false;
    Worker() {
        std::thread([&]() {
            while ( not badhappened );
            // kill the work
        }).detach();
    }
    int WorkComponent {
        if ( badhappening() )
            badhappened = true;
        return someint;
    }
    void DoWork {
        // WorkComponents called several times
    }
}

But I don't know what to call at kill the work. It's not a problem for DoWork to happen in a separate thread, but there doesn't appear to be an equivalent pthread_kill in C++'s threads. Is there a solution that doesn't involve putting several if(badhappened) return; calls into DoWork?

like image 266
Mike Barriault Avatar asked Oct 17 '12 13:10

Mike Barriault


1 Answers

Long story short:

There is no safe way to stop a non-cooperative thread.

Yes, there are tools to forcibly shut down a thread but you are asking for trouble. The only safe way is to agree on a termination policy. This boils down to checking a flag sufficiently frequently as you write.

More on this from the gurus:

C++ and Beyond 2011: Scott, Andrei and Herb - Ask Us Anything

See at 30:44 What's the deal with systematic and principled thread termination and program termination?


Canceling a thread is not a good idea in POSIX either:

Cancelling a thread using pthread_cancel : good practice or bad

like image 67
Ali Avatar answered Oct 07 '22 12:10

Ali