-1

I have seen the How to properly stop the Thread in Java?. But there is no try&catch in C.

I call a JNI function in a thread. I want to stop the thread when something goes wrong.

What should I do in error() to prevent the code behind and stop the thread?

When I call error() in function 1, how to avoid subsequent function execution?

My code like this:

new Thread() (new Runnable() {
        @Override
        public void run() {
            JNIfunction();
        }
    }).start();

JNIfunction():

while(flag) {
    //Function1, call error() to stop thread when wrong.
    //Function2, call error() to stop thread when wrong.
    //Function3, call error() to stop thread when wrong.
    ...
}

error():

void error() {
    flag= 0;
}
loRe
  • 3
  • 4

2 Answers2

1

Set flag=0. It will exit the loop and the thread will end naturally.

Chloe
  • 25,162
  • 40
  • 190
  • 357
0

Use boolean volatile variable to track in case of error and then stop thread by using interrupt().
Similar kind of question is answered in detail How to properly stop the Thread in Java?

Haripriya
  • 822
  • 1
  • 14
  • 27
  • I have seen that question.There is no try&catch in C. When I call error() in function 1, how to avoid subsequent function execution? – loRe Sep 22 '18 at 06:36
  • Check if you have got expected value in returned object from C call, else set boolean volatile variable true to stop the flow, call interrupt() and throw custom exception from your error(). I am asking to check status at every C call, thus subsequent executions can be avoided. – Haripriya Sep 22 '18 at 09:10
  • Thank you. I finally used setjmp/longjmp to simulate try/catch in c. – loRe Sep 23 '18 at 13:58
  • @loRe Please provide code you have used and mark it as accepted answer, it would be helpful for others, it can also be checked for enhancement if any required. – Haripriya Sep 24 '18 at 07:52
  • 1
    in JNIFunciton: flag = 0==setjmp(return_buf); while(flag) { //Function1, call error() to stop thread when wrong. //Function2, call error() to stop thread when wrong. //Function3, call error() to stop thread when wrong. ... } function error(): void error() { longjmp(return_buf, 1); } – loRe Oct 02 '18 at 11:59
  • It seems that i can't format the code in the comment. – loRe Oct 02 '18 at 12:13