5

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • 3
    You could use Boost threads instead, as they have termination points that can be checked (which is not much different than checking a variable I admit). However, forcibly killing a thread might be bad, especially if the thread has allocated resources. – Some programmer dude Oct 17 '12 at 13:55
  • @JoachimPileborg `pthread_kill`, to my knowledge, can send a similar termination signal that `kill` does. I imagine there's a similar mechanic in `std::thread`, just don't know what it is. @MartinJames That could work actually, it shouldn't happen often enough to be a noticeable performance hit. Good idea, thanks! – Mike Barriault Oct 17 '12 at 14:03
  • Unfortunately there are no such features in `std::thread`, but I hope it comes in the next C++ standard (whenever that comes). However, you can use the [`std::thread::native_handle`](http://en.cppreference.com/w/cpp/thread/thread/native_handle) function to get the native pthread (hopefully) handle and then call `pthread_kill`. – Some programmer dude Oct 17 '12 at 14:08

1 Answers1

6

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

Community
  • 1
  • 1
Ali
  • 56,466
  • 29
  • 168
  • 265