取消 pthread 似乎很奇怪

Cancellation of pthread seems weird

我有一个简单的测试,在将此函数分配为工作函数时取消 pthread:

static void * thread_start(void *arg)
{
    printf("New thread started\n");
    pthread_cleanup_push(cleanup_handler, NULL);
    pthread_cancel(pthread_self());
    pthread_testcancel();           /* A cancellation point */
    return NULL;
}

cleanup_handler:

static void cleanup_handler(void *arg)
{
    printf("Called clean-up handler\n");
}

但是我得到一些无关语法错误的编译器错误(在其他地方缺少'}')。另一方面,如果我像这样添加 pthread_cleanup_pop(1):

static void * thread_start(void *arg)
{
    printf("New thread started\n");
    pthread_cleanup_push(cleanup_handler, NULL);
    pthread_cancel(pthread_self());
    pthread_testcancel();           /* A cancellation point */
    pthread_cleanup_pop(1);  //added this
    return NULL;
}

它按预期进行编译和 运行(pthread_cleanup_pop(1) 不是 运行)。 cleanup_handler 被执行并且线程 returns PTHREAD_CANCLED.

最后有 pthread_cleanup_pop(1) 是完全不相关的,因为当线程即将终止时,所有清理处理程序都应该总是 运行。如果没有我取消,我什至不在乎它们是否 运行。

怎么了?

已解决

正在查看the man

POSIX.1 permits pthread_cleanup_push() and pthread_cleanup_pop() to be implemented as macros that expand to text containing '{' and '}', respectively. For this reason, the caller must ensure that calls to these functions are paired within the same function, and at the same lexical nesting level. (In other words, a clean-up handler is established only during the execution of a specified section of code.)

强调我的