In the previous tutorial, we discussed how to create a thread in an application. In this tutorial, the following program shows how a running thread can be cancelled from the main thread.
Source code to test thread cancellation
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *my_thread_function(void *arg);
int main() {
int result;
pthread_t my_thread_a;
void *thread_result;
result = pthread_create(&my_thread_a, NULL, my_thread_function, NULL);
if (result != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
sleep(1);
printf("Canceling thread...\n");
result = pthread_cancel(my_thread_a);
if (result != 0) {
perror("Thread cancelation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish...\n");
result = pthread_join(my_thread_a, &thread_result);
if (result != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.