pthread_cleanup_push导致语法错误

时间:2014-07-01 06:39:16

标签: c pthreads mutex

我尝试在代码中添加一个部分,以便在取消时解锁互斥锁。这可能会发生并导致死锁。因此,我尝试添加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]。

1 个答案:

答案 0 :(得分:9)

您必须在匹配的对中致电pthread_cleanup_push()pthread_cleanup_pop(),而且您的代码段没有pthread_cleanup_pop()来电。

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

  

这些功能可以实现为宏。申请书   确保它们作为陈述出现,并在同一对中出现   词法范围(即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)