pthread_cleanup_push导致语法错误

我尝试在我的代码中添加一个部分,它可以在取消的情况下解锁互斥锁。 这可能会发生并导致死锁。 因此我尝试添加pthread_cleanup_push(cleanup_unlock_mutex, &mutex_ftdi); 但是这行会导致语法错误,我将其添加到代码文件末尾。 如果我注释代码行,程序将编译没有任何错误。 我做错了什么?

 void cleanup_unlock_mutex(void *p){ pthread_mutex_unlock(p); } ....... }else{ for(unsigned count=0; count <= number_of_requests; count++){ pthread_cleanup_push(cleanup_unlock_mutex, &mutex_ftdi); pthread_mutex_lock(&mutex_ftdi); process_requests(count, numberofthread); pthread_mutex_unlock(&mutex_ftdi); } } // compiler error: error: expected 'while' before '}' token .......... 

文件中的所有其他函数都会收到警告:ISO C禁止嵌套函数[-pedantic]。

您必须在匹配对中调用pthread_cleanup_push()pthread_cleanup_pop() ,并且您的代码段没有pthread_cleanup_pop()调用。

http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cleanup_pop.html上的文档解释了原因:

这些function可以实现为宏。 应用程序应确保它们作为语句出现,并且在同一个词法范围内成对出现(也就是说, pthread_cleanup_push()宏可以被认为扩展到一个令牌列表,其第一个令牌为'{'pthread_cleanup_pop()扩展为令牌列表,其最后一个令牌是对应的'}' )。

为了使这个具体,一个可能的实现,取自glibc的nptl/sysdeps/pthread/pthread.h

 /* Install a cleanup handler: ROUTINE will be called with arguments ARG when the thread is canceled or calls pthread_exit. ROUTINE will also be called with arguments ARG when the matching pthread_cleanup_pop is executed with non-zero EXECUTE argument. pthread_cleanup_push and pthread_cleanup_pop are macros and must always be used in matching pairs at the same nesting level of braces. */ # define pthread_cleanup_push(routine, arg) \ do { \ __pthread_cleanup_class __clframe (routine, arg) /* Remove a cleanup handler installed by the matching pthread_cleanup_push. If EXECUTE is non-zero, the handler function is called. */ # define pthread_cleanup_pop(execute) \ __clframe.__setdoit (execute); \ } while (0)