I have a pthread that I created and now I want that in a specific time interval the thread execute some code. But the user should also be able to cancel the thread. How can I cancel a thread and ensure that the thread is not cancelled when it execute the code?
In Java you handle this with
while(!isInterrupted)
Is there any similar solution with pthreads.
In the Question’s example code you are checking some variable. This is not the normal pattern for interrupting threads in Java.
In Java, you interrupt a thread by calling the
interrupt()method.The thread then checks if it is interrupted inside IO and system calls (which can throw
InterruptedExceptionwhen this happens; this means a thread that is sleeping or waiting on IO can be awoken when interrupted) or by sampling theisInterrupted()flag (typically used in a condition in a loop, as in Question).The distinction is important; checking some flag variable you’ve declared is only possible in loops and your own code; the Java interrupting system works for all threads and all non-CPU-blocking code without special effort on the part of the programmer.
Pthreads has the
pthread_cancel()pattern which works like the Java interrupting pattern.