Created
October 8, 2013 16:02
-
-
Save lingling2012/6887042 to your computer and use it in GitHub Desktop.
Use pthread_cancel, pthread_setcancelstate, pthread_setcanceltype to Cancel a thread.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <pthread.h> | |
void *thread_func(void *arg); | |
int main(void) { | |
int rs; | |
pthread_t thd; | |
void *thread_result; | |
rs = pthread_create(&thd, NULL, thread_func, NULL); | |
if (rs != 0) { | |
perror("Thread creation failed!\n"); | |
exit(EXIT_FAILURE); | |
} | |
sleep(3); | |
rs = pthread_cancel(thd); | |
if (rs != 0) { | |
perror("Thread cancelation failed\n"); | |
exit(EXIT_FAILURE); | |
} | |
rs = pthread_join(thd, &thread_result); | |
if (rs != 0) { | |
perror("Thread Join failed\n"); | |
exit(EXIT_FAILURE); | |
} | |
exit(EXIT_FAILURE); | |
} | |
void *thread_func(void *arg) { | |
int i, rs; | |
rs = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); | |
if (rs != 0) { | |
perror("Thread pthread_setcancelstate failed\n"); | |
exit(EXIT_FAILURE); | |
} | |
// PTHREAD_CANCEL_DEFERRED means that it will wait the pthread_join, | |
// pthread_cond_wait, pthread_cond_timewait.. to be call when the | |
// thread receive cancel message. | |
rs = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); | |
if (rs != 0) { | |
perror("Thread pthread_setcanceltype failed\n"); | |
exit(EXIT_FAILURE); | |
} | |
printf("thread_func is running\n"); | |
for (i = 0; i < 10; i++) { | |
perror("Thread is stil running (%d) ... \n", i); | |
sleep(1); | |
} | |
pthread_exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment