简体   繁体   中英

How can I cancel a thread using C++?

POSIX provides the function pthread_cancel to cancel thread execution but seems C++ does not provide a such function Also is it possible to use a mix std::thread and pthread_cancel?? I also see on linux system, std::thread is a wrapper of POSIX thread

Although there is no exact replacement for pthread_cancel, you can come close with jthread .

The class jthread represents a single thread of execution. It has the same general behavior as std::thread, except that jthread automatically rejoins on destruction, and can be cancelled/stopped in certain situations.

This will not interrupt the thread, but still relies on "cooperative" mechanisms. The running jthread will have to keep polling it's stop token and stop by itself.

A good example can be found here .

    std::jthread sleepy_worker([] (std::stop_token stoken) {
        for(int i=0; i < 10; i++) {
            std::this_thread::sleep_for(300ms);
            if(stoken.stop_requested()) {
                std::cout << "Sleepy worker is requested to stop\n";
                return;
            }
            std::cout << "Sleepy worker goes back to sleep\n";
        }
    });
    sleepy_worker.request_stop();
    sleepy_worker.join();

But to bluntly answer your question: no, there is (currently, c++20) no portable way of cancelling a thread.

PS: Actually "killing" a thread (or anything for that matter) is something that should usually be avoided. As such I personally doubt you'll ever see a mechanism for it in ISOC++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM