gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:39:57 25 4
gpt4 key购买 nike

假设您有一些无法修改的外部同步代码,您要求它异步运行,但也要求它是可取消的。如果外部代码阻塞,那么我有两个选择。

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

B) 取消执行

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

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();
}

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

最佳答案

简答:

除非是关键任务,否则不要取消/终止线程执行。请改用方法“A”。

长答案:

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

win32

你可以用 TerminateThread 终止一个线程函数,但是:

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

MSDN 说:

TerminateThread is a dangerous function that should only be used in the most extreme cases.

线程

这里的情况稍微好一些。当 pthread_cancel 时,您有机会释放您的资源被调用,但是:

  • 默认情况下,目标线程终止于 cancellation points .这意味着您无法取消没有任何取消点的代码。基本上,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;
}

你可能会看到:

  • 从不在 Windows 上调用析构函数。
  • 删除 pthread_setcanceltype 会导致挂起。
  • 可以捕获内部 pthread 异常。

关于c++ - std::promise 外部代码,异步取消,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com