C++0x thread interruption

后端 未结 8 1308
谎友^
谎友^ 2020-11-29 04:28

According to the C++0x final draft, there\'s no way to request a thread to terminate. That said, if required we need to implement a do-it-yourself solution.

On the o

相关标签:
8条回答
  • 2020-11-29 04:46

    All the language specification says that the support isn't built into the language. boost::thread::interrupt needs some support from the thread function, too:

    When the interrupted thread next executes one of the specified interruption points (or if it is currently blocked whilst executing one)

    i.e. when the thread function doesn't give the caller a chance to interrupt, you are still stuck.

    I'm not sure what you mean with "going native" - there is no native support, unless you are spellbound to boost:threads.

    Still, I'd use an explicit mechanism. You have to think about having enough interruption points anyway, why not make them explicit? The extra code is usually marginal in my experience, though you may need to change some waits from single-object to multiple-objects, which - depending on your library - may look uglier.


    One could also pull the "don't use exceptions for control flow", but compared to messing around with threads, this is just a guideline.

    0 讨论(0)
  • 2020-11-29 04:49

    Its unsafe to terminate a thread, since you would have no control over the state of any data-structures is was working on at that moment.

    If you want to interrupt a running thread, you have to implement your own mechanism. IMHO if you need that, your design is not prepared for multiple threads.

    If you just want to wait for a thread to finish, use join() or a future.

    0 讨论(0)
  • 2020-11-29 04:54

    It is unsafe to terminate a thread preemptively because the state of the entire process becomes indeterminate after that point. The thread might have acquired a critical section prior to being terminated. That critical section will now never be released. The heap could become permanently locked, and so on.

    The boost::thread::interrupt solution works by asking nicely. It will only interrupt a thread doing something thats interruptible, like waiting on a Boost.Thread condition variable, or if the thread does one of these things after interrupt is called. Even then, the thread isn't unceremoniously put through the meat grinder as, say, Win32's TerminateThread function does, it simply induces an exception, which, if you've been a well-behaved coder and used RAII everywhere, will clean up after itself and gracefully exit the thread.

    0 讨论(0)
  • 2020-11-29 04:56

    Here is my humble implementation of a thread canceller (for C++0x). I hope it will be useful.

    // Class cancellation_point
    #include <mutex>
    #include <condition_variable>
    
    struct cancelled_error {};
    
    class cancellation_point
    {
    public:
        cancellation_point(): stop_(false) {}
    
        void cancel() {
            std::unique_lock<std::mutex> lock(mutex_);
            stop_ = true;
            cond_.notify_all();
        }
    
        template <typename P>
        void wait(const P& period) {
            std::unique_lock<std::mutex> lock(mutex_);
            if (stop_ || cond_.wait_for(lock, period) == std::cv_status::no_timeout) {
                stop_ = false;
                throw cancelled_error();
            }
        }
    private:
        bool stop_;
        std::mutex mutex_;
        std::condition_variable cond_;
    };
    
    
    // Usage example
    #include <thread>
    #include <iostream>
    
    class ThreadExample
    {
    public:
        void start() {
            thread_ = std::unique_ptr<std::thread>(
                new std::thread(std::bind(&ThreadExample::run, this)));
        }
        void stop() {
            cpoint_.cancel();
            thread_->join();
        }
    private:
        void run() {
            std::cout << "thread started\n";
            try {
                while (true) {
                    cpoint_.wait(std::chrono::seconds(1));
                }
            } catch (const cancelled_error&) {
                std::cout << "thread cancelled\n";
            }
        }
        std::unique_ptr<std::thread> thread_;
        cancellation_point cpoint_;
    };
    
    int main() {
        ThreadExample ex;
        ex.start();
        ex.stop();
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 05:01

    Implementing a do-it-yourself solution makes the most sense, and it really should not be that hard to do. You will need a shared variable that you read/write synchronously, indicating whether the thread is being asked to terminate, and your thread periodically reads from this variable when it is in a state where it can safely be interrupted. When you want to interrupt a thread, you simply write synchronously to this variable, and then you join the thread. Assuming it cooperates appropriately, it should notice that that the variable has been written and shut down, resulting in the join function no longer blocking.

    If you were to go native, you would not gain anything by it; you would simply throw out all the benefits of a standard and cross-platform OOP threading mechanism. In order for your code to be correct, the thread would need to shut down cooperatively, which implies the communication described above.

    0 讨论(0)
  • 2020-11-29 05:02

    My implementation of threads uses the pimpl idiom, and in the Impl class I have one version for each OS I support and also one that uses boost, so I can decide which one to use when building the project.

    I decided to make two classes: one is Thread, which has only the basic, OS-provided, services; and the other is SafeThread, which inherits from Thread and has method for collaborative interruption.

    Thread has a terminate() method that does an intrusive termination. It is a virtual method which is overloaded in SafeThread, where it signals an event object. There's a (static) yeld() method which the running thread should call from time to time; this methods checks if the event object is signaled and, if yes, throws an exception caught at the caller of the thread entry point, thereby terminating the thread. When it does so it signals a second event object so the caller of terminate() can know that the thread was safely stopped.

    For cases in which there's a risk of deadlock, SafeThread::terminate() can accept a timeout parameter. If the timeout expires, it calls Thread::terminate(), thus killing intrusively the thread. This is a last-resource when you have something you can't control (like a third-party API) or in situations in which a deadlock does more damage than resource leaks and the like.

    Hope this'll be useful for your decision and will give you a clear enough picture about my design choices. If not, I can post code fragments to clarify if you want.

    0 讨论(0)
提交回复
热议问题