pthread_cancel() in C with example
Last Updated :
06 Sep, 2017
prerequisite: Multithreading, pthread_self() in C with Example
pthread_cancel() = This function cancel a particular thread using thread id. This function send a cancellation request to the thread.
Syntax : – int pthread_cancel(pthread_t thread);
First Program : – Cancel self thread
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * calls( void * ptr)
{
printf ( "GeeksForGeeks" );
pthread_cancel(pthread_self());
return NULL;
}
int main()
{
pthread_t thread ;
pthread_create(& thread , NULL, calls, NULL);
pthread_join( thread , NULL);
return 0;
}
|
Output:
GeeksForGeeks
If you use Linux then compile this program gcc program_name.c -lpthread
Second Program : – Cancel other thread
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
int counter = 0;
pthread_t tmp_thread;
void * func( void * p)
{
while (1) {
printf ( "thread number one\n" );
sleep(1);
counter++;
if (counter = = 2) {
pthread_cancel(tmp_thread);
pthread_exit(NULL);
}
}
}
void * func2( void * p)
{
tmp_thread = pthread_self();
while (1) {
printf ( "thread Number two" );
sleep(1);
}
}
int main()
{
pthread_t thread_one, thread_two;
pthread_create(&thread_one, NULL, func, NULL);
pthread_create(&thread_two, NULL, func2, NULL);
pthread_join(thread_one, NULL);
pthread_join(thread_two, NULL);
}
|
Output:
thread number one
thread number two
thread number one
thread number two
If you use Linux then compile this program gcc program_name.c -lpthread
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...