简体   繁体   English

如何使用 C++ 取消线程?

[英]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?? POSIX 提供了 function pthread_cancel 来取消线程执行,但似乎 C++ 没有提供这样的 function p_cancelthread 和混合线程? I also see on linux system, std::thread is a wrapper of POSIX thread我还在 linux 系统上看到,std::thread 是 POSIX 线程的包装器

Although there is no exact replacement for pthread_cancel, you can come close with jthread .尽管 pthread_cancel 没有确切的替代品,但您可以使用jthread来接近。

The class jthread represents a single thread of execution. class jthread 表示单个执行线程。 It has the same general behavior as std::thread, except that jthread automatically rejoins on destruction, and can be cancelled/stopped in certain situations.它具有与 std::thread 相同的一般行为,除了 jthread 在销毁时自动重新加入,并且可以在某些情况下取消/停止。

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.正在运行的 jthread 必须不断轮询它的停止令牌并自行停止。

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.但是直截了当地回答你的问题:不,(目前,c++20)没有可移植的方式来取消线程。

PS: Actually "killing" a thread (or anything for that matter) is something that should usually be avoided. PS:实际上“杀死”一个线程(或与此相关的任何事情)通常应该避免。 As such I personally doubt you'll ever see a mechanism for it in ISOC++.因此,我个人怀疑您是否会在 ISOC++ 中看到它的机制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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