【问题标题】:pthread_cleanup_push causes Syntax errorpthread_cleanup_push 导致语法错误
【发布时间】:2014-08-21 15:16:21
【问题描述】:

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

【问题讨论】:

  • } 错过了。你能先缩进代码吗?奇怪的!!!! else 没有 ifwhile 循环在哪里?发布整个代码。
  • but I do not want to post the if section of the code.如果你不想,那么任何人都不想给你答案。
  • @IrgendwPointer :我相信您只有 pthread 行代码会导致问题,这就是您不想显示代码的原因,但请考虑显示一段可编译/可运行的代码,以便任何人都可以尝试找出您的错误并给您答复
  • 为什么这个问题被关闭了?它显然有足够的信息来诊断和回答。它甚至可能对可能遇到相同问题的人有所帮助。

标签: c pthreads mutex


【解决方案1】:

您必须成对调用pthread_cleanup_push()pthread_cleanup_pop(),并且您的sn-p 没有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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多