Sunday, April 12, 2009

pthread_cancel in POSIX thread

Here is an example to use pthread_cancel in POSIX thread programming.

cancelthread.c Select all

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

void cleanup_routine(void *arg)
{
int *c = (int*)arg;
printf("ThreadCleanup: cleanup called at counter %d\n", *c);
}

void *threadFunc(void *arg)
{
char *str;
int i = 0;
int oldstate;
int retval;

pthread_cleanup_push(cleanup_routine, &i);

pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, &oldstate);

str=(char*)arg;
i = 0;
while(i < 110 )
{
usleep(1);
printf("threadFunc says: %s %d\n",str,i);
if ((i % 10)==0) {
pthread_testcancel();
printf("pthread_testcancel\n");
}
++i;
}
pthread_cleanup_pop(0);
return NULL;
}

int main(void)
{
pthread_t pth; // this is our thread identifier
pthread_attr_t attr;
void *result;
int status;
int join_status;
int i = 0;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

pthread_create(&pth,&attr,threadFunc,"foo");

while(i < 100)
{
usleep(1);
printf("main is running... %d\n",i);
if (i==20) {
printf("thread is terminating...\n");
status = pthread_cancel(pth);
break;
}

++i;
}

printf("main waiting for thread to terminate...\n");
status = pthread_join(pth,&result);
if (status != 0)
printf("Error: Join thread");
if (result == PTHREAD_CANCELED)
printf ("Thread canceled at iteration\n");
else
printf ("Thread was not canceled\n");
printf("main with thread terminated\n");

return 0;
}

 
 

No comments: