std :: promise外部代码,异步取消

ary*_*naq 8 c++ asynchronous c++11

假设您有一些无法修改的外部同步代码,并且您需要它来运行异步,但也要求它可以取消.如果外部代码阻塞,那么我有两个选项.

A)欺骗用户并让我的异步方法在取消时立即返回,很清楚代码仍然在某处运行完成.

B)取消执行

我想为选项B实现一个接口

namespace externallib {
std::uint64_t timeconsuming_operation()
{
    std::uint64_t count = 0;
    for (auto i = 0; i < 1E+10; ++i)
    {
        count++;
    }
    return count;
}
}




template <typename R>
struct async_operation
{

    struct CancelledOperationException
    {
        std::string what() const
        {
            return what_;
        }
    private:
        std::string what_{ "Operation was cancelled." };
    };

    template<typename Callable>
    async_operation(Callable&& c)
    {
        t_ = std::thread([this, c]()
        {
            promise_.set_value(c());  // <-- Does not care about cancel(), mostly because c() hasn't finished..
        });
    }


    std::future<R> get()
    {
        return promise_.get_future();
    }


    void cancel()
    {
        promise_.set_exception(std::make_exception_ptr(CancelledOperationException()));
    }

    ~async_operation()
    {
        if (t_.joinable())
            t_.join();
    }

private:
    std::thread t_;
    std::promise<R> promise_;
};

void foo()
{
    async_operation<std::uint64_t> op([]()
    {
        return externallib::timeconsuming_operation();
    });

    using namespace std::chrono_literals;
    std::this_thread::sleep_for(5s);

    op.cancel(); 
    op.get();
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我无法解决外部代码被阻塞的限制,如果有的话,如何可以提前取消执行?

iva*_*ult 5

简短回答:

除非关键任务,否则不要取消/终止线程执行.使用方法"A"代替.

答案很长:

正如@Caleth指出的那样,没有标准的或跨平台的方式来做到这一点.您所能做的就是获取线程的本机句柄并使用特定于平台的功能.但是有一些重要的陷阱.

的win32

您可以使用TerminateThread函数终止线程,但是:

  • 堆栈变量不会被破坏
  • thread_local变量不会被破坏
  • DLL 将不会被通知

MSDN说:

TerminateThread是一个危险的函数,只能在最极端的情况下使用.

并行线程

这里情况略好一些.pthread_cancel在被叫时你有机会释放你的资源,但是:

  • 默认情况下,目标线程终止于取消点.这意味着您无法取消没有任何取消点的代码.基本上,for(;;);不会被取消在所有.
  • 一旦达到取消点,就会抛出特定于实现的异常,因此可以正常释放资源.
  • 请记住,这个异常可以被try/ 捕获catch,但需要重新抛出.
  • 可以通过禁用此行为pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr);.但是如果不满足取消点,则不会释放资源(对于win32)

例

#include <iostream>
#include <thread>
#include <chrono>

#if defined(_WIN32)
#include <Windows.h>
void kill_thread(HANDLE thread) {
    TerminateThread(thread, 0);
}
#else 
#include <pthread.h>
void kill_thread(pthread_t thread) {
    pthread_cancel(thread);
}
#endif

class my_class {
public:
    my_class()  { std::cout << "my_class::my_class()"  << std::endl; }
    ~my_class() { std::cout << "my_class::~my_class()" << std::endl; }
};

void cpu_intensive_func() {
#if !defined(_WIN32)
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr);
#endif
    my_class cls;
    for(;;) {}
}

void io_func() {
    my_class cls;
    int a;
    std::cin >> a;
}

void io_func_with_try_catch() {
    my_class cls;
    try {
        int a;
        std::cin >> a;  
    } catch(...) {
        std::cout << "exception caught!" << std::endl;
        throw;
    }
}

void test_cancel(void (*thread_fn) (void)) {
    std::thread t(thread_fn);
    std::this_thread::sleep_for(std::chrono::seconds(1));
    kill_thread(t.native_handle());    
    t.join();
    std::cout << "thread exited" << std::endl;
    std::cout << "--------------------" << std::endl;
}

int main() {
    test_cancel(cpu_intensive_func);
    test_cancel(io_func);
    test_cancel(io_func_with_try_catch);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你可能会看到:

  • 析构函数永远不会在windows上调用.
  • 移除pthread_setcanceltype导线挂起.
  • pthread可以捕获内部异常.


Cal*_*eth 2

没有可移植的方法可以在线程想要结束之前结束它。

根据您的平台,可能有多种结束线程的方法,您可能需要使用这些方法std::thread::native_handle。这很可能导致未定义的行为,所以我不推荐它。