@ Naruil's suggestion to call pthread_cancel () is the best solution I have found, but it will not work if you did not follow these steps.
According to the pthread_cancel man page, pthread_cancelibility depends on two things
- thread_cancel_state.
- thread_cancel_type.
thread_cancel_state by default is PTHREAD_CANCEL_ENABLE, so our main problem is thread_cancel_type , by default it is type PTHREAD_CANCEL_DEFFERED, but we need PTHREAD_CANCEL_ASYNCHRONOUS to set this thread, which we wan't to cancel.
Following an example:
#include <stdio.h> #include <pthread.h> void *thread_runner(void* arg) { //catch the pthread_object as argument pthread_t obj = *((pthread_t*)arg); //ENABLING THE CANCEL FUNCTIONALITY int prevType; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &prevType); int i=0; for( ; i < 11 ; i++)//1 - > 10 { if(i == 5) pthread_cancel(obj); else printf("count -- %d", i); } printf("done"); } int main(int argc, char *argv[]) { pthread_t obj; pthread_create(&obj, NULL, thread_runner, (void*)&obj); pthread_join(obj, NULL); return 0; }
run it with gcc filename.c -lpthread and print the following: count - 0 count - 1 count - 2 count - 3 count - 4
note that the done is never printed because the stream was canceled when I became 5 and the current stream was canceled. Special thanks to @Naruil for suggesting "pthread_cancel".
source share