I am using the following code:
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void
clean(void *arg)
{
printf("thread clean: %ld\n", (unsigned long)arg);
}
void*
thread_template(void *arg)
{
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
pthread_cleanup_push(clean, (void*)pthread_self());
printf("thread: %ld\n", (unsigned long)pthread_self());
while ( 1 ) {}
pthread_cleanup_pop(0);
pthread_exit((void*)0);
}
int
main(int argc, char const *argv[]) {
pthread_t tid;
pthread_create(&tid, NULL, thread_template, NULL);
// waiting for 2 seconds
sleep(2);
pthread_cancel(tid);
pthread_join(tid, NULL);
}
It works fine both on FreeBSD 11 and Ubuntu 16, outputs are like this:
thread: 1994462320
thread clean: 1994462320
But on macOS, it seems pthread_cancel() doesn't affect the thread, main thread blocks at pthread_join(), the clean function never execute(only the first row was output).
So, what happened to macOS's pthread? or any wrong with my code ?