Transferred from: http://blog.csdn.net/huangshanchun/article/details/47420961
Copyright NOTICE: Welcome to reprint, if there are deficiencies, please treatise.
One thread can call Pthread_cancel to terminate another thread in the same process, but it is worth emphasizing that, between threads in the same process, pthread_cancel terminates the signal to another Cheng. The system does not close the canceled thread immediately, and only the thread will actually end when the next system call is canceled. or call Pthread_testcancel to let the kernel detect if the current thread needs to be canceled. The canceled thread, the exit value, defines the value of the constant pthread_canceled in the Linux pthread Library is-1.
[CPP]View PlainCopy
- #include <pthread.h>
- int pthread_cancel (pthread_t thread);
See the following procedure:
[CPP]View PlainCopy
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- void *thread_fun (void *arg)
- {
- int i=1;
- printf ("thread start \ n");
- While (1)
- {
- i++;
- }
- return (void *) 0;
- }
- int main ()
- {
- void *ret=null;
- int iret=0;
- pthread_t Tid;
- Pthread_create (&tid,null,thread_fun,null);
- Sleep (1);
- Pthread_cancel (TID); //Cancel thread
- Pthread_join (Tid, &ret);
- printf ("Thread 3 exit code%d\n", (int) ret);
- return 0;
- }
Will find that the program continues to run, the thread can not be canceled, the reason Pthread_cancel to another line Cheng stop signal. The system does not close the canceled thread immediately, and only the thread will actually end when the next system call is canceled. If the thread does not perform a system call, it can be resolved using Pthread_testcancel.
[CPP]View PlainCopy
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- void *thread_fun (void *arg)
- {
- int i=1;
- printf ("thread start \ n");
- While (1)
- {
- i++;
- Pthread_testcancel ();
- }
- return (void *) 0;
- }
- int main ()
- {
- void *ret=null;
- int iret=0;
- pthread_t Tid;
- Pthread_create (&tid,null,thread_fun,null);
- Sleep (1);
- Pthread_cancel (TID); //Cancel thread
- Pthread_join (Tid, &ret);
- printf ("Thread 3 exit code%d\n", (int) ret);
- return 0;
- }
Linux pthread_cancel cannot cancel the thread's cause "go"