我使用以下代码:
#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);
}
在FreeBSD 11和Ubuntu 16上都可以正常工作 输出是这样的:
主题:1994462320
线程清洁:1994462320
但是在macOS上,似乎pthread_cancel()不会影响线程,pthread_join()中的主线程块,clean函数永远不会执行(只输出第一行)。
那么,macOS的pthread发生了什么?或者我的代码有什么问题吗?