pthread_cancel() does not work in Mac OS X

I wrote a simple sample program to illustrate that pthread_cancel() does not work on Mac OS X (checked on 10.2, 10.3 and 10.4). Does anyone know why is that and if it may be fixed?

Thanks!

Example program:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void CleanupFunc(void *p)
{
fprintf(stderr, "Cleanup\n");
}

void * AThreadFunc(void *p)
{
pthread cleanuppush(CleanupFunc, 0);

sleep(20);

pthread cleanuppop(1);
return 0;
}

int main()
{
pthread_t thr;

pthread_create(&thr, 0, AThreadFunc, 0);

sleep(2);
pthread_cancel(thr);

sleep(10);

return 0;
}


The program is meant to write string "Cleanup", which means that the cleanup function is called. Investigation showed that pthread_cancel() does not have any effect on the thread. At the same time this program works as expected on Linux and Solaris.

Posted on Dec 13, 2005 6:51 AM

Reply
1 reply

Dec 28, 2005 8:09 AM in response to Andrei Tarassov

Hi Andrei,
pthread_cancel() isn't implemented on Darwin. This topic has been discussed for some time on the emailing lists. For example on the Darwin kernel list , a poster makes the good point that thread cancellation isn't usually a good way to go. Rather, having child threads poll a global and exiting gracefully when a state, or condition, is reached is a better way to go.

If you want to read more from the Apple mailing lists on pthread_cancel(), here's some search results I get.

Good luck!

Ed

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

pthread_cancel() does not work in Mac OS X

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.