简体   繁体   English

如何取消具有本机代码(C / C ++)的任务?

[英]How to cancel a task that has native code (C/C++)?

Background 背景

I have a short yet heavy task that uses NDK (JNI) in order to do some bitmap manipulation. 我有一个简短而繁重的任务,该任务使用NDK(JNI)进行一些位图操作。

On some cases, I need to cancel the task and go to other things. 在某些情况下,我需要取消任务并执行其他操作。

However, since the task uses a lot of memory too, and in the end also creates a large bitmap, this could cause out-of-memory errors. 但是,由于该任务也占用大量内存,并且最后还会创建一个较大的位图,因此可能会导致内存不足错误。

The question 问题

How should I cancel a task that has native code in it? 如何取消包含本机代码的任务? Is there a best practice for this? 是否有最佳做法?

Maybe some kind of interrupted exception that I can use for C/C++, so that as soon as it is caught, I can at least free all of the memory? 也许我可以将某种中断的异常用于C / C ++,以便一旦捕获到该异常,就可以至少释放所有内存?

Maybe I should add some kind of listener (observer) to the native code? 也许我应该在本地代码中添加某种侦听器(观察者)? Or maybe I should call a method that I need to assume the caller has? 或者也许我应该调用假设调用者具有的方法?

The simplest way? 最简单的方法?

Spin the task on a thread. 在线程上旋转任务。 You may spin the thread in Java and call into JNI from there. 您可以在Java中旋转线程并从那里调用JNI。 It's easier than pthreads. 它比pthread容易。

Introduce a volatile flag (boolean variable), set it to false on task startup. 引入易失性标志(布尔变量),在任务启动时将其设置为false。

In the task, check the stop flag as often as it's practical. 在任务中,尽可能实际地检查停止标志。 If true, abandon the task (you might throw an exception to return through several levels of function nesting, but you don't have to). 如果为true,则放弃该任务(您可能会引发异常以通过函数嵌套的多个级别返回,但不必这样做)。

When you want to cancel, set the flag from the main thread. 要取消时,请从主线程设置标志。 Wait for the task to notice that. 等待任务注意到这一点。

This won't work well if the slowest part of the task is calling a library/OS function - that function won't check for the flag. 如果任务中最慢的部分是调用库/ OS函数,则此方法将无法正常工作-该函数将不检查标志。

There's no safe builtin mechanism in C++ for correctly terminating a thread of code that does not want to be terminated (maybe signals, but they kill the whole process, not a thread). C ++中没有安全的内置机制来正确终止不想终止的代码线程(也许发出信号,但它们杀死了整个过程,而不是线程)。 Periodically checking for the flag is what I mean by "wanting to be terminated". 定期检查标志是我“希望终止”的意思。

I've seen this approach used before, and I think the best approach would be to create a isCancelled() method that you can call periodically from your native code in order to determine when to stop. 我以前见过这种方法,我认为最好的方法是创建一个isCancelled()方法,您可以从本地代码中定期调用该方法以确定何时停止。 If you're using AsyncTask , that method should already exist. 如果您使用的是AsyncTask ,则该方法应该已经存在。

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

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