pthreads-3: Canceling a thread

Threads once created using pthread_create,can some times be required to be stopped in between before they complete their execution.
This can be done using the function


pthread_cancel will by default stop the thread immediately. This behavior can be modified by using the attribute pthread_setcancelstate.
In the program that executes as part of the thread, we can add a series of sleep, giving us enough time to see it creation and the calling the cancel from the parent thread.

Thus the function to be executed by the thread will be

Note: The working of pthread_create is given in the post pthread creation

In the main thread, we will wait for a while after creating the thread and then call the pthread_cnacel.

After calling the pthread_cancel, we also need to call pthread_join to terminate the thread successfully.
The return value recieved by pthread_join on a cancelled thread is PTHREAD_CANCELLED, which is equal to integer "-1".
Thus let us print the return value and see what the thread returned.
The full code will look as follows.


Compile it using the -pthread option and execute it.


Thus we see that the thread stopped executing before finishing the for loop and the return value is -1, which indicates that the thread was cancelled using pthread_cancel

Follow by Email