Friday, May 17, 2013

How can one thread cancel another thread ? Simple program to demostrate this using pthread_cancel(3).
=====================================

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_function(void *);
int err;
int main( )
{
pthread_t tid;
void *retval;

if((err = pthread_create(&tid, NULL, thread_function, NULL)))
{
fprintf( stderr, "PTHREAD_CREATE ERROR: %s\n", strerror(err) ) ;
exit(0);
}
sleep(2);
if( (err = pthread_cancel(tid)) != 0 )
{
fprintf( stderr, "PTHREAD_CANCEL ERROR: %s\n", strerror(err) ) ;
exit(1);
}

if( (err = pthread_join(tid, &retval )) != 0 )
{
fprintf( stderr, "PTHREAD_JOIN ERROR: %s\n", strerror(err) ) ;
exit(2);
}

printf("*************MAIN*****************\n");
printf("My thread id = %u\n", pthread_self());
printf("My process id = %u\n", getpid());
printf( "Return value = %d\n", (int)retval);

}

void *thread_function( void *arg )
{
int i;
if( (err = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) != 0) //Try PTHREAD_CANCEL_DEFERRED
{
fprintf( stderr, "PTHREAD_SETCANCELTYPE ERROR: %s\n", strerror(err) ) ;
exit(3);
}
if( (err = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)) != 0 )
{
fprintf( stderr, "PTHREAD_SETCANCELSTATE ERROR: %s\n", strerror(err) ) ;
exit(4);
}
printf("************THREAD*****************\n");
printf("My thread id = %u\n", pthread_self());
printf("My process id = %u\n", getpid());
printf("The argument that is passed to me is %p\n", arg);

for( i = 0; ; i++ )
{
printf( "Thread = %d \n", i );

}
pthread_exit((int *)4);
}

No comments:

Post a Comment