2016-09-15 57 views
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 */ 
    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被执行并且线程返回PTHREAD_CANCLED。

最后得到pthread_cleanup_pop(1)是完全不相干的,因为当一个线程即将被终止时,所有的清理处理程序应该总是运行。我甚至不关心他们是否在没有取消的情况下运行。

出了什么问题?

解决

回答

1

the man

POSIX.1允许pthread_cleanup_push()和pthread_cleanup_pop()寻找到 被实现为宏扩大,分别 '{' 和 '}' 文本含。 因此,调用者必须确保对这些函数的调用在相同函数中进行配对,并且在相同的词汇嵌套级别上进行配对 。(换句话说,一个清理处理只是 代码的指定部分的执行过程中建立 。)

重点煤矿

+0

对,就是它,谢谢!现在一切都很有意义。 – user2908112